package org.jeecg.modules.zhoupackage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jeecg.modules.degression.mapper.MlccPriceSystemPingleiMapper;
import org.jeecg.modules.degression.mapper.MyMlccPriceSystemCostRecordMapper;
import org.jeecg.modules.degression.pojo.MlccPriceSystemCostRecord;
import org.jeecg.modules.degression.pojo.MlccPriceSystemPinglei;
import org.jeecg.modules.gwcjava.jiekou.entity.MlccUserInfo;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.mapper.MyErrorOrderMapper;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.mapper.MyMlccCompanyInfoMapper;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.mapper.MyMlccTrackafterorderPersonMapper;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.mapper.OrderCenterMapper;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.pojo.MlccCompanyInfo;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.pojo.MlccErrorOrder;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.pojo.MlccTrackafterorderPerson;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.pojo.MyAfterProduct;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.service.IOrderCenterService;
import org.jeecg.modules.zhouAdmin.admin.util.SingleAndTeamOrderUtil;
import org.jeecg.modules.zhoupackage.mapper.*;
import org.jeecg.modules.zhoupackage.pojo.*;
import org.jeecg.modules.zhoupackage.pojo.myexcel.FuwujiaEntity;
import org.jeecg.modules.zhoupackage.pojo.myexcel.MyteamPriceProduct;
import org.jeecg.modules.zhoupackage.pojo.myexcel.PengProductEntity;
import org.jeecg.modules.zhoupackage.pojo.myexcel.ProSize;
import org.jeecg.modules.zhoupackage.service.ITeamOrderService;
import org.jeecg.modules.zhoupackage.util.FabricUtil;
import org.jeecg.modules.zhoupackage.util.MyExcelUtils;
import org.jeecg.modules.zhoupackage.util.TeamOrderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@SuppressWarnings("all")
@Service
public class TeamOrderServiceImpl implements ITeamOrderService {

    @Autowired
    IOrderCenterService orderService;

    @Autowired
    MyMlccProductInfoMapper productInfoMapper;

    @Autowired
    MlccFabricInfoMapper fabricInfoMapper;

    @Autowired
    MyMlccCategoryInfoMapper categoryInfoMapper;

    @Autowired
    MyContrastColorMapper contrastColorMapper;

    @Autowired
    FabricUtil fabricUtil;

    @Autowired
    MyTeamMudoleMapper teamMudoleMapper;

    @Autowired
    MyTeamOrderMapper teamOrderMapper;

    @Autowired
    MyMlccModuleSmallTemplateMapper smallTemplateMapper;

    @Autowired
    MyEmbroColorMapper embroColorMapper;

    @Autowired
    TeamOrderUtil teamOrderUtil;

    @Autowired
    MyDepartProductMapper departProductMapper;

    @Autowired
    MyStrandardInfoMapper strandardInfoMapper;

    @Autowired
    MyBodySizeMapper bodySizeMapper;

    @Autowired
    MyCustomerDepartMapper customerDepartMapper;

    @Autowired
    MyCustomeInfoMapper customeInfoMapper;

    @Autowired
    MyMlccModuleSmallTemplateMapper moduleSmallTemplateMapper;

    @Autowired
    MyProductBodySizeMapper productBodySizeMapper;

    @Autowired
    MyMlccButtonsInfoMapper buttonsInfoMapper;

    @Autowired
    MySizeInfoMapper sizeInfoMapper;

    @Autowired
    MysmallProductMapper smallProductMapper;

    @Autowired
    MyMlccFanxiuMapper fanxiuMapper;

    @Autowired
    MyXiaoBodysizeMapper xiaoBodysizeMapper;

    @Autowired
    MyMlccAafterSalesinfoMapper afterSalesinfoMapper;

    @Autowired
    MyTrackingOrderMapper trackingOrderMapper;

    @Autowired
    MysmallProductMapper SmallProductMapper;

    @Autowired
    MyMlccTrackingTeamDepartMapper trackingTeamDepartMapper;

    @Autowired
    MyMlccBatchPackingInfoMapper batchPackingInfoMapper;

    @Autowired
    TeamOrderAafterTMapper teamOrderAafterTMapper;

    @Autowired
    MlccPriceSystemPingleiMapper priceSystemPingleiMapper;

    @Autowired
    MyPriceIntervalMapper priceIntervalMapper;

    @Autowired
    MyMlccPriceSystemCostRecordMapper recordMapper;

    @Autowired
    MyMlccBusinessWaterInfoMapper waterInfoMapper;

    @Autowired
    MyMlccBusinessWaterInfoMapper businessWaterInfoMapper;

    @Autowired
    FontMapper fontMapper;

    @Autowired
    MyLocatiomMapper locatiomMapper;

    @Autowired
    MyEmbroColorMapper fontColorMapper;

    @Autowired
    SingleAndTeamOrderUtil singleUtil;

    @Autowired
    CartMlccUserInfoMapper userInfoMapper;

    @Autowired
    MyMlccDiscountPricesysytemMapper discountPricesysytemMapper;

    @Autowired
    MyErrorOrderMapper errorOrderMapper;

    @Autowired
    MlccOrderFabricMapper orderFabricMapper;

    @Autowired
    MyMlccMaterialLibuInfoMapper libuInfoMapper;

    @Autowired
    MyMlccDilinniInfoMapper dilinniInfoMapper;

    @Autowired
    MyMlccEventRecrodInfoMapper eventRecrodInfoMapper;

    @Autowired
    MyMlccstoreMapper storeMapper;

    @Autowired
    MyMlccCompanyInfoMapper companyInfoMapper;

    @Autowired
    MlccCartInfoMapper cartInfoMapper;

    @Autowired
    MyMlccSingleOrderInfoMapper singleOrderInfoMapper;

    @Autowired
    MyMlccTrackafterorderPersonMapper trackafterorderPersonMapper;

    @Autowired
    OrderCenterMapper mapper;

    @Autowired
    MyMlccEmbdtypePriceMapper embdtypePriceMapper;


    /**
     * 团订里面定制款查看详细
     *
     * @param productId 产品ID
     */
    @Override
    public MlccProductInfo getDetail(String productId) {
        MlccProductInfo productInfo = productInfoMapper.selectById(productId);
        if (productInfo != null) {
            /*查询面料信息*/
            if (productInfo.getFabricIds() != null) {
               /* // 这个产品的面料id
                ArrayList<String> fabricid = new ArrayList<>();*/
                String[] split = productInfo.getFabricIds().split(",");
                QueryWrapper<MlccFabricInfo> fabricWrapper = new QueryWrapper<>();
                fabricWrapper.in("id", Arrays.asList(split));
                productInfo.setFabricInfoList(fabricInfoMapper.selectList(fabricWrapper));
            }

            /*查询里布信息*/
            if (productInfo.getLibuId() != null) {
                MlccMaterialLibuInfo libuInfo = libuInfoMapper.selectById(productInfo.getLibuId());
                if (libuInfo != null) {
                    productInfo.setLibuName(libuInfo.getLibuCode());
                }
            }

            /*查询低领尼信息*/
            if (productInfo.getDilinliId() != null) {
                MlccDilinniInfo dilinniInfo = dilinniInfoMapper.selectById(productInfo.getDilinliId());
                if (dilinniInfo != null) {
                    productInfo.setDilinniName(dilinniInfo.getDilinniNumber());
                }
            }

            /*查询纽扣信息*/
            if (productInfo.getButtonsIds() != null) {
                MlccButtonsInfo buttonsInfo = buttonsInfoMapper.selectById(productInfo.getButtonsIds());
                if (buttonsInfo != null) {
                    productInfo.setButtonName(buttonsInfo.getButtonsName());
                }
            }

            /*查询款式与工艺*/
            if (productInfo.getCategoryIds() != null) {
                String[] split = productInfo.getCategoryIds().split(",");
                QueryWrapper<MlccCategoryInfo> categoryWrapper = new QueryWrapper<>();
                categoryWrapper.in("id", Arrays.asList(split));
                List<MlccCategoryInfo> categoryInfos = categoryInfoMapper.selectList(categoryWrapper);
                for (MlccCategoryInfo info : categoryInfos) {
                    if (info != null) {
                        MlccModuleSmallTemplate smallTemplate = cartInfoMapper.getSmall(info.getParentId());
//                        MlccModuleSmallTemplate smallTemplate = smallTemplateMapper.selectById(info.getParentId());
                        if (smallTemplate != null) {
                            info.setSmallTemplateName(smallTemplate.getParameter());
                        }
                    }
                }
                productInfo.setCategoryInfo(categoryInfos);
            }
            /*查询撞色数据*/
            if (productInfo.getZhuangseIds() != null) {
                List<MlccContrastcolorInfo> contrastcolorInfos = new ArrayList<>();
                String[] split = productInfo.getZhuangseIds().split(",");
                if (split != null && split.length > 0) {
                    for (String idAndColorName : split) {
                        // 拿到具体的撞色id和颜色名称
                        String[] split1 = idAndColorName.split("/");
                        MlccContrastcolorInfo info = contrastColorMapper.selectById(split1[0]);
                        if (info != null) {
                            if (split1.length > 1) {
                                info.setColorName(split1[1]);
                            }
                            contrastcolorInfos.add(info);
                        }
                    }
                }
                /*QueryWrapper<MlccContrastcolorInfo> contrastcolorWrapper = new QueryWrapper<>();
                contrastcolorWrapper.in("id", Arrays.asList(split));
                List<MlccContrastcolorInfo> contrastcolorInfos = contrastColorMapper.selectList(contrastcolorWrapper);
                *//*给撞色数据查询具体的颜色*//*
                for (MlccContrastcolorInfo info : contrastcolorInfos) {
                    MlccEmbroideredColor color = embroColorMapper.selectById(info.getEmColorId());
                    if (color != null)
                        info.setColorName(color.getColorName());
                }*/
                productInfo.setContrastcolorList(contrastcolorInfos);
            }

            // 查询绣字字体
            if (productInfo.getXiuziZiti() != null) {
                MlccEmbroideredFont font = fontMapper.selectById(productInfo.getXiuziZiti());
                if (font != null) {
                    productInfo.setXiuziZiti(font.getEmbroideredName());
                }
            }

            // 查询绣字部位
            if (productInfo.getXiuziWeizhi() != null) {
                MlccCategoryLocaltion localtion = locatiomMapper.selectById(productInfo.getXiuziWeizhi());
                if (localtion != null) {
                    productInfo.setXiuziWeizhi(localtion.getXiuziLocaltion());
                }
            }

            // 查询绣字颜色
            if (productInfo.getXiuziColor() != null) {
                MlccEmbroideredColor color = fontColorMapper.selectById(productInfo.getXiuziColor());
                if (color != null) {
                    productInfo.setXiuziColor(color.getColorName());
                }
            }

            // 查询绣字高度
            if (productInfo.getXiuziHeight() != null) {
                MlccEmbdtypePrice height = embdtypePriceMapper.selectById(productInfo.getXiuziHeight());
                if (height != null) {
                    productInfo.setXiuziHeight(height.getEmbroideredHeight());
                }
            }


            /*下一步*/
            // 7、获取产品中的尺寸信息(身体数据，注意与体型表区别)
            if (productInfo.getBodySizeIds() != null) {
                HashSet<MlccProductBodysize> bodySizeSet = new HashSet<>();
                // 用产品ID可以到达产品尺寸关联表
                QueryWrapper<MlccProductBodysize> wrapper5 = new QueryWrapper<>();
                wrapper5.eq("product_id", productInfo.getId()).eq("isfanxiu", 0);
                List<MlccProductBodysize> productBodysizes = productBodySizeMapper.selectList(wrapper5);
                for (MlccProductBodysize bodysize : productBodysizes) {
                    // 根据查询到的尺寸，区分是净体尺寸还是成衣尺寸
                    MlccBodySizeInfo bodySizeInfo = bodySizeMapper.selectById(bodysize.getBodysizeId());
                    if (bodySizeInfo != null) {
                        bodysize.setIsJin(bodySizeInfo.getIsJin());
                    }
                    bodySizeSet.add(bodysize);
                }
                for (MlccProductBodysize probodysize : bodySizeSet) {
                    String categoryId = bodySizeMapper.selectById(probodysize.getBodysizeId()).getCategoryId();
                    probodysize.setTypeName(categoryInfoMapper.selectById(categoryId).getCategoryName());
                    probodysize.setSizeName(bodySizeMapper.selectById(probodysize.getBodysizeId()).getBodySizename());
                    probodysize.setUnit(bodySizeMapper.selectById(probodysize.getBodysizeId()).getUnit());
                }
                /*ArrayList<MlccProductBodysize> list = new ArrayList<>(bodySizeSet);*/
                /*for (int i = 0; i < list.size() - 1; i++) {
                    for (int j = 1; j < list.size(); j++) {
                        if (list.get(i).getBodysizeId().equals(list.get(j).getBodysizeId()) && list.get(i).getBodysizeValue().equals(list.get(j).getBodysizeValue())) {
                            list.remove(i);
                        }
                    }
                }*/
                /*HashSet<MlccProductBodysize> set = new HashSet<>(list);*/
                // 成衣尺寸与净体尺寸分开
                Map<Integer, List<MlccProductBodysize>> collect = bodySizeSet.stream().collect(Collectors.groupingBy(MlccProductBodysize::getIsJin));
                // 0是成衣尺寸
                List<MlccProductBodysize> cheng = collect.get(0);
                // 1是净体尺寸
                List<MlccProductBodysize> jing = collect.get(1);
                productInfo.setProductBodySizeList(bodySizeSet);
                productInfo.setCheng(cheng);
                productInfo.setJing(jing);
            }

            // 查询客户名称
            if (productInfo.getOrderSn() != null && !"".equals(productInfo.getOrderSn())) {
                // 说明这是个订，只有个订的产品才会有订单编号
                QueryWrapper<MlccSingleOrderInfo> wrapper = new QueryWrapper<>();
                wrapper.eq("order_sn", productInfo.getOrderSn());
                MlccSingleOrderInfo singleOrderInfo = singleOrderInfoMapper.selectOne(wrapper);
                if (singleOrderInfo != null) {
                    productInfo.setCustomerName(singleOrderInfo.getCustomerName());
                }
            }
        }
        return productInfo;
    }

    /**
     * 团订的产品列表
     *
     * @param token
     * @param pageNo
     * @param pageSize
     */
    @Override
    public IPage<MlccProductInfo> getProList(String token, Integer pageNo, Integer pageSize) {
        if (!fabricUtil.checkToken(token)) return null;
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        QueryWrapper<MlccProductInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userDetail.getId());
        Page<MlccProductInfo> page = new Page<>(pageNo, pageSize);
        return productInfoMapper.selectPage(page, wrapper);
    }

    /**
     * 团订的模板删除
     *
     * @param moudleSn
     */
    @Override
    public int moduleDel(String moudleSn) {
        QueryWrapper<MlccTeamModuleInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", moudleSn);
        MlccTeamModuleInfo info = teamMudoleMapper.selectOne(wrapper);
        info.setStatus(2);
        return teamMudoleMapper.updateById(info);
    }

    /**
     * 团订的订单删除
     *
     * @param orderSn
     */
    @Override
    public int OrderDel(String orderSn) {
        QueryWrapper<MlccTeamOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccTeamOrderInfo info = teamOrderMapper.selectOne(wrapper);
        info.setStatus(-1);
        return teamOrderMapper.updateById(info);
    }

    /**
     * 编辑团订模板(查询详情)
     *
     * @param moduleSn
     */
    @Override
    public MlccTeamModuleInfo updateModule(String moduleSn) {
        return teamOrderUtil.updateModule(moduleSn);
    }

    /**
     * 根据部门ID和订单编号查询产品列表
     *
     * @param departid
     * @param orderSn
     */
    @Override
    public List<MlccProductInfo> getProduct(String departid, String orderSn) {
        QueryWrapper<MlccDepartProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("customer_depart_id", departid);
        // 拿到部门下的产品ID
        HashSet<String> productids = new HashSet<>();
        List<MlccDepartProduct> products = departProductMapper.selectList(wrapper);
        for (MlccDepartProduct product : products) {
            productids.add(product.getProductId());
        }
        // 查询具体的产品列表
        QueryWrapper<MlccProductInfo> wrapper1 = new QueryWrapper<>();
//        wrapper1.eq("order_sn", orderSn).in("id", productids);
        wrapper1.in("id", productids);
        return productInfoMapper.selectList(wrapper1);
    }

    /**
     * 团订界面尺码选择（查询标准尺码父级）
     *
     * @param categoryIds 选中产品的类别ID，多个用逗号隔开
     */
    @Override
    public Set<MlccStandardInfo> sizeChose(String categoryIds) {
        String[] split = categoryIds.split(",");
        HashSet<MlccStandardInfo> result = new HashSet<>();
        for (String cateid : split) {
            // 只查询版号
            MlccCategoryInfo categoryInfo = categoryInfoMapper.selectById(cateid);
            if (categoryInfo != null && categoryInfo.getIsType() == 3) {
                QueryWrapper<MlccStandardInfo> wrapper = new QueryWrapper<>();
                wrapper.like("category_id", cateid);
                List<MlccStandardInfo> infos = strandardInfoMapper.selectList(wrapper);
                for (MlccStandardInfo info : infos) {
                    result.add(info);
                }
            }
        }
        return result;
    }

    /**
     * 根据选中的标准尺码查询和净体尺寸
     *
     * @param topid
     */
    @Override
    public Map<String, List<MlccStandardInfo>> getSizeButtons(String topid) {
        HashMap<String, List<MlccStandardInfo>> map = new HashMap<>();
        QueryWrapper<MlccStandardInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", topid).eq("is_ketiao", 1).eq("is_jin", 0);

        QueryWrapper<MlccStandardInfo> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("parent_id", topid).eq("is_jin", 1);
        map.put("Size", strandardInfoMapper.selectList(wrapper));
        map.put("jintiSize", strandardInfoMapper.selectList(wrapper2));
        return map;
    }

    /**
     * 获取自定义尺寸
     *
     * @param categoryids
     */
    @Override
    public Set<MlccBodySizeInfo> getCustomSize(String categoryids) {
        String[] split = categoryids.split(",");
        HashSet<MlccBodySizeInfo> set = new HashSet<>();
        for (String id : split) {
            QueryWrapper<MlccBodySizeInfo> wrapper = new QueryWrapper<>();
            wrapper.like("category_id", id).orderByAsc("id");
            List<MlccBodySizeInfo> infos = bodySizeMapper.selectList(wrapper);
            for (MlccBodySizeInfo info : infos) {
                set.add(info);
            }
        }
        return set;
    }

    /**
     * 团订订单预览
     *
     * @param orderSn 订单编号
     */
    @Override
    public MlccTeamOrderInfo previewOrder(String orderSn) {
        return orderDetail(orderSn);
    }

    /**
     * 团订订单详情（跟着部门、产品走的版本）预览订单
     */
    @Async
    public MlccTeamOrderInfo orderDetail(String orderSn) {
        long startTime = System.currentTimeMillis();
        QueryWrapper<MlccTeamOrderInfo> wrapper = new QueryWrapper<>();
        List<MlccFabricInfo> allFabric = new ArrayList<>(); // 存放订单里所有的面料
        List<MlccFabricInfo> keFabric = new ArrayList<>(); // 存放订单里所有的客供面料
        List<MlccProductInfo> allPro = new ArrayList<>();// 存放订单下所有产品
        BigDecimal fabricPriceAll = new BigDecimal(0); // 订单下所有面料的价格
        double proPriceAall = 0; // 订单下所有产品的价格（加工费用）
        wrapper.eq("order_sn", orderSn);
        MlccTeamOrderInfo info = teamOrderMapper.selectOne(wrapper);// 首先拿到了订单基本信息
        MlccUserInfo userDetail = userInfoMapper.selectById(info.getUserId());
        // 创建一个变量，用来计算订单价格
        BigDecimal orderMoney = new BigDecimal(0);
        if (info != null && info.getCustomerId() != null) {
            // 客户基本信息
            MlccCustomerInfo customerInfo1 = customeInfoMapper.selectById(info.getCustomerId());
            info.setCustomerInfo(customerInfo1);
            /*1、订单里的部门列表*/
            QueryWrapper<MlccCustomerDepart> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("customer_id", info.getCustomerId());
            List<MlccCustomerDepart> departList = customerDepartMapper.selectList(wrapper1);// 这里拿到了所有部门
            if (departList != null && departList.size() > 0) {
                for (MlccCustomerDepart depart : departList) {

                    /*新需求，查询部门下的小产品，替代部门下的人员ID*/
                    // 只查询30个，剩余的人员在excel中进行查看
                    Page<MlccCustomerProductInfo> infoPage = new Page<>(1, 30);
                    QueryWrapper<MlccCustomerProductInfo> customerProductInfoQueryWrapper = new QueryWrapper<>();
                    customerProductInfoQueryWrapper.eq("team_order_sn", orderSn).eq("depart_id", depart.getId());
                    IPage<MlccCustomerProductInfo> iPage = SmallProductMapper.selectPage(infoPage, customerProductInfoQueryWrapper);
                    List<MlccCustomerProductInfo> mlccCustomerProductInfos = iPage.getRecords();
//                    List<MlccCustomerProductInfo> mlccCustomerProductInfos = SmallProductMapper.selectList(customerProductInfoQueryWrapper);
                    if (mlccCustomerProductInfos != null && mlccCustomerProductInfos.size() > 0) {

                        // 优化01，
                        mlccCustomerProductInfos.stream().forEach(sallpro -> {
                            if (sallpro != null) {
                                // 查人员
                                MlccCustomerInfo customerInfo = customeInfoMapper.selectById(sallpro.getCustomerId());
                                // 查产品
                                MlccProductInfo mlccProductInfo = productInfoMapper.selectById(sallpro.getProductId());
                                if (customerInfo != null) {
                                    // 赋值
                                    sallpro.setCustomerName(customerInfo.getCustomerName()).setSex(customerInfo.getSex())
                                            .setCustomerCode(customerInfo.getCustomerCode()).setProductName(mlccProductInfo.getProductName());
                                }
                            }
                        });
                    }
                    depart.setSmallPro(mlccCustomerProductInfos);

                    /*3、得到部门下产品列表*/
                    QueryWrapper<MlccDepartProduct> wrapper3 = new QueryWrapper<>();
                    wrapper3.eq("customer_depart_id", depart.getId());
                    List<MlccDepartProduct> departProducts = departProductMapper.selectList(wrapper3);// 所有的部门产品关联
                    ArrayList<MlccProductInfo> productInfos = new ArrayList<>(); // 用来存放部门下所有的产品
                    // 查询部门下的所有产品
                    if (departProducts != null && departProducts.size() > 0) {
                        // 优化02
                        departProducts.stream().forEach(departProduct -> {
                            QueryWrapper<MlccProductInfo> mlccProductInfoQueryWrapper = new QueryWrapper<>();
                            mlccProductInfoQueryWrapper.eq("id", departProduct.getProductId());
                            MlccProductInfo mlccProductInfo = productInfoMapper.selectOne(mlccProductInfoQueryWrapper);
                            if (mlccProductInfo != null) {
                                productInfos.add(mlccProductInfo);
                                allPro.add(mlccProductInfo);
                            }
                        });
                    }
                    if (productInfos != null && productInfos.size() > 0) {
                        /*4、接下来要查询产品里的信息*/
                        for (MlccProductInfo newProductInfo : productInfos) {

                            // 查询这个大产品名下有多少个小产品
                            QueryWrapper<MlccCustomerProductInfo> smallwrapper = new QueryWrapper<>();
                            smallwrapper.eq("product_id", newProductInfo.getId());
                            // 产品数量
                            int smallCount = smallProductMapper.selectCount(smallwrapper);

                            // 1、查询产品的数量
                            if (newProductInfo.getCategoryIds() != null) {
                                List<String> CategoryIdSet = Arrays.asList(newProductInfo.getCategoryIds().split(","));// 每个产品中的类别ID
                                /*2、品类版型的查询（产品数据中categoryid对应数据的isType为1的数据）*/
                                QueryWrapper<MlccCategoryInfo> wrapper4 = new QueryWrapper<>();
                                /*wrapper2.in("id", CategoryIdSet).eq("is_type", 1);*/
                                wrapper4.in("id", CategoryIdSet).eq("is_type", 1);
                                List<MlccCategoryInfo> plbxs = categoryInfoMapper.selectList(wrapper4);
                                // 给每一个品类查询他的上级名称，就是模块下的小模块表的名称
                                if (plbxs != null && plbxs.size() > 0) {
                                    for (MlccCategoryInfo plbx : plbxs) {
                                        if (plbx != null && plbx.getParentId() != null) {
                                            MlccModuleSmallTemplate smallTemplate = moduleSmallTemplateMapper.selectById(plbx.getParentId());
                                            if (smallTemplate != null && smallTemplate.getParameter() != null) {
                                                plbx.setSmallTemplateName(smallTemplate.getParameter());
                                            }
                                        }
                                    }
                                    newProductInfo.setPlbx(plbxs);
                                }
                            }
                            // 3、从产品数据中查询面料数据
                            if (newProductInfo.getFabricIds() != null && !"".equals(newProductInfo.getFabricIds())) {
                                double zhekou = 1;
                                // 存放这个产品的下的所有面料
                                HashSet<MlccFabricInfo> fabricInfoSet = new HashSet<>();
                                // 查询产品的面料ids 面料id/购买米数
                                List<String> fabricids = Arrays.asList(newProductInfo.getFabricIds().split(","));
                                for (String fabricid : fabricids) {
                                    String[] split = fabricid.split("/");
                                    // 查询到面料的基本信息
                                    MlccFabricInfo mlccFabricInfos = fabricInfoMapper.selectById(split[0]);
                                    if (mlccFabricInfos != null && !"-999999".equals(mlccFabricInfos.getFabricCode())) {
                                        // 重新查询面料的价格(拿到了标准单价)
                                        Double mishu = Double.valueOf(split[1]);
                                        if (smallCount > 0) {
                                            mishu = mishu * smallCount;
                                        }
                                        mlccFabricInfos = fabricUtil.addPrice(mlccFabricInfos, mishu);
                                        if (mlccFabricInfos != null) {
                                            if (mlccFabricInfos.getGroupId() != null && !"".equals(mlccFabricInfos.getGroupId())) {
                                                // 获取面料折扣
                                                zhekou = fabricUtil.userFabricDiscount(userDetail.getId() + "", mlccFabricInfos.getGroupId());
                                            }
                                            mlccFabricInfos.setKehuzk(zhekou);
                                            mlccFabricInfos.setMishu(mishu + "");
                                            fabricInfoSet.add(mlccFabricInfos);
                                            if (mlccFabricInfos.getMishu() != null && !"0".equals(mlccFabricInfos.getMishu())) {
                                                // 面料一定会选择米数，没有米数的不是面料，忽略
                                                // 加入所有面料集合之前进行判断，集合里面是否已经有这个面料了，有的话累加
                                                int addFResult = 0;
                                                for (MlccFabricInfo ff : allFabric) {
                                                    // 如果原来就有这个面料，累加！！！
                                                    if (mlccFabricInfos.getFabricCode().equals(ff.getFabricCode())) {
                                                        double lastmishu = Double.valueOf(mlccFabricInfos.getMishu()) + Double.valueOf(ff.getMishu());
                                                        ff.setMishu(lastmishu + "");
                                                        addFResult = -1;// 负数就说明这个面料已经添加过了
                                                        break; // 添加了直接跳出训话
                                                    } else {
                                                        // 否则进入下一个比较
                                                        addFResult++;
                                                        continue;
                                                    }
                                                }
                                                // 只有添加结果大于0，说明这个面料不重复，需要添加
                                                if (addFResult > 0 || allFabric.size() == 0) {
                                                    mlccFabricInfos.setProductid(newProductInfo.getId());
                                                    allFabric.add(mlccFabricInfos);
                                                }
                                            }
                                        }
                                    } else if (mlccFabricInfos != null && "-999999".equals(mlccFabricInfos.getFabricCode())) {
                                        // 带上产品id和产品名称
                                        mlccFabricInfos.setProductid(newProductInfo.getId()).setFabricName(newProductInfo.getProductName());
                                        // 这里说明是客供面料芜湖
                                        // 重新查询面料的价格(拿到了标准单价)
                                        Double mishu = Double.valueOf(split[1]);
                                        if (smallCount > 0) {
                                            mishu = mishu * smallCount;
                                        }
                                        mlccFabricInfos.setMishu(mishu + "");
                                        keFabric.add(mlccFabricInfos);
                                    }
                                }
                            }

                            /*下一步*/
                            // 8、加工费用（也就是产品费用）
                            if (newProductInfo.getZhehouPrice() != null) {
                                double orderPrice = 0;
                                Double kehuzhekou = fabricUtil.getkhzktd(orderSn);// 客户折扣
                                newProductInfo.setKhzk(kehuzhekou);
                                newProductInfo.setAfterzhekouPrice(newProductInfo.getZhehouPrice().doubleValue() * kehuzhekou);
                                newProductInfo.setAllPrice(newProductInfo.getZhehouPrice().doubleValue() * kehuzhekou);
                                orderPrice += newProductInfo.getAllPrice();
                            }

                            /*下一步*/
                            // 11 计算订单金额
                            /*if (newProductInfo.getZhehouPrice() != null) {
                                Double khzk = fabricUtil.getkhzktd(orderSn);
                                // 计算出产品的折后价格
                                BigDecimal proPrice = newProductInfo.getZhehouPrice().multiply(new BigDecimal(khzk));
                                orderMoney = orderMoney.add(proPrice);
                            }*/
                            proPriceAall += newProductInfo.getAfterzhekouPrice();
                        }
                    }
                    depart.setProductInfos(productInfos);
                }
            }

            // 在计算面料之前，对重复面料进行过滤面料，并累加基础米数
            /*for (int i = 0; i < allFabric.size() - 1; i++) {
                for (int j = 1; j < allFabric.size(); j++) {
                    System.out.println(allFabric.get(i).getFabricCode());
                    System.out.println(allFabric.get(j).getFabricCode());
                    System.out.println("难道不一样？？？？？" + allFabric.get(i).getFabricCode().equals(allFabric.get(j).getFabricCode()));
                    if (allFabric.get(i).getFabricCode().equals(allFabric.get(j).getFabricCode())) {
                        double lastmishu = Double.valueOf(allFabric.get(i).getMishu()) + Double.valueOf(allFabric.get(j).getMishu());
                        allFabric.get(i).setMishu(lastmishu + "");
                        allFabric.remove(j);
                    }
                }
            }*/

            // 计算面料价格
            for (MlccFabricInfo fabricInfo : allFabric) {
                // 计算折后单价
                BigDecimal zhehouPrice = fabricInfo.getFabricPrice().multiply(new BigDecimal(fabricInfo.getKehuzk()));
                if ("-999999".equals(fabricInfo.getFabricCode())) {
                    zhehouPrice = new BigDecimal(0);
                    fabricInfo.setAfterPrice(0);
                } else {
                    fabricInfo.setAfterPrice(zhehouPrice.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
                // 计算单重面料的总价
                BigDecimal zongjia = zhehouPrice.multiply(new BigDecimal(Double.valueOf(fabricInfo.getMishu())));
//                double zongjia = new BigDecimal(fabricInfo.getAfterPrice() * Double.valueOf(fabricInfo.getMishu())).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                fabricInfo.setAllPrice(zongjia.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

                // 查询订单面料关联表是否有对应的记录，如果有，折从哪里获取准确的数据
                QueryWrapper<MlccOrderFabric> orderFabricQueryWrapper = new QueryWrapper<>();
                orderFabricQueryWrapper.eq("order_sn", orderSn).eq("fabric_id", fabricInfo.getId());
                MlccOrderFabric orderFabric = orderFabricMapper.selectOne(orderFabricQueryWrapper);
                if (orderFabric != null) {
                    fabricInfo.setMishu(orderFabric.getMishu()).setFabricPrice(orderFabric.getPrice())
                            .setAfterPrice(orderFabric.getZhehouPrice().doubleValue()).setAllPrice(orderFabric.getAllprice().doubleValue());
                }

                // 面料的总价
                fabricPriceAll = fabricPriceAll.add(new BigDecimal(fabricInfo.getAllPrice()));
                //订单总价
                orderMoney = orderMoney.add(new BigDecimal(fabricInfo.getAllPrice()));
            }
            // 如果这个时候是草稿订单，跟新一下订单金额
            if (info.getStatus() == 0) {
                info.setOrderMoney(orderMoney.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "");
                teamOrderMapper.updateById(info);
            }
            info.setDeparts(departList);// 部门里以经查到了下面的员工和产品信息
        }


        // 遍历以下客供面料
        for (MlccFabricInfo ke : keFabric) {
            // 查询订单面料关联表是否有对应的记录，如果有，折从哪里获取准确的数据
            QueryWrapper<MlccOrderFabric> orderFabricQueryWrapper = new QueryWrapper<>();
            orderFabricQueryWrapper.eq("order_sn", orderSn).eq("fabric_id", ke.getId()).eq("productid", ke.getProductid());
            MlccOrderFabric orderFabric = orderFabricMapper.selectOne(orderFabricQueryWrapper);
            if (orderFabric != null) {
                ke.setMishu(orderFabric.getMishu()).setRemark(orderFabric.getRemark());
            }
        }

        fabricPriceAll = fabricPriceAll.setScale(2, BigDecimal.ROUND_HALF_UP);
        info.setAllFabric(allFabric).setFabricPriceAll(fabricPriceAll.doubleValue()).setAllPro(allPro).setProPriceAall(proPriceAall);
        info.setKeFabric(keFabric);
        System.out.println("总耗时====" + (System.currentTimeMillis() - startTime));
        return info;
    }

    /**
     * 团订订单预览界面立即下单
     *
     * @param orderSn 订单编号
     */
    @Override
    public int orderNow(String orderSn) {
        QueryWrapper<MlccTeamOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccTeamOrderInfo info = teamOrderMapper.selectOne(wrapper);
        info.setStatus(11);
        return teamOrderMapper.updateById(info);
    }

    /**
     * 前端——我的订单——团订返修，获取订单基本信息
     *
     * @param token   令牌
     * @param orderSn 订单编号
     */
    @Override
    public MlccTeamOrderInfo getBaseTeamOrderDetail(String token, String orderSn) {
        // 订单基本信息
        QueryWrapper<MlccTeamOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccTeamOrderInfo teamOrderInfo = teamOrderMapper.selectOne(wrapper);

        // 查询支付时间
        QueryWrapper<MlccTrackingOrder> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("order_sn", orderSn).eq("order_status", 1);
        MlccTrackingOrder trackingOrder = trackingOrderMapper.selectOne(wrapper2);
        if (trackingOrder != null) {
            teamOrderInfo.setPayTime(trackingOrder.getCreateTime());
        }

        // 查询下单电源
        if (teamOrderInfo != null && teamOrderInfo.getUserId() != null && !"".equals(teamOrderInfo.getUserId())) {
            MlccUserInfo mlccUserInfo = userInfoMapper.selectById(teamOrderInfo.getUserId());
            if (mlccUserInfo != null) {
                teamOrderInfo.setEmpName(mlccUserInfo.getRealname()).setEmpPhone(mlccUserInfo.getPhone());
            }
        }

        // 查询客户信息
        // 获取客户编号和客户名称（也就是获取门店对应的公司编号和名称）
        if (teamOrderInfo != null && teamOrderInfo.getStoreId() != null) {
            MlccStoreInfo storeInfo = storeMapper.selectById(teamOrderInfo.getStoreId());
            if (storeInfo != null) {
                teamOrderInfo.setStoreName(storeInfo.getStoreName());
                MlccCompanyInfo companyInfo = companyInfoMapper.selectById(storeInfo.getCompanyId());
                if (companyInfo != null) {
                    teamOrderInfo.setCompanyName(companyInfo.getCompanyName()).setCompanyCode(companyInfo.getCompanyCode());
                }
            }
        }

        // 订单的客户基本信息
        if (teamOrderInfo != null && teamOrderInfo.getCustomerId() != null) {
            MlccCustomerInfo customerInfo = customeInfoMapper.selectById(teamOrderInfo.getCustomerId());
            teamOrderInfo.setCustomerInfo(customerInfo);
        }
        return teamOrderInfo;
    }

    /**
     * 团订返修根据小产品编号获取员工列表（实际获取单个员工）
     *
     * @param token        令牌
     * @param orderSn      订单编号
     * @param smallProCode 小产品编码
     * @return 人员数据
     */
    @Override
    public List<MlccCustomerInfo> getempList(String token, String orderSn, String smallProCode) {
        QueryWrapper<MlccCustomerProductInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("code", smallProCode);
        // 拿到人员产品关联表（小产品）
        MlccCustomerProductInfo one = smallProductMapper.selectOne(wrapper);
        if (one == null) return null;
        MlccProductInfo productInfo = productInfoMapper.selectById(one.getProductId()); // 拿到对应的产品
        if (one == null) return null;
        String id = one.getCustomerId();
        List<MlccCustomerInfo> list = new ArrayList<>();
        MlccCustomerInfo customerInfo = customeInfoMapper.selectById(id);
        MlccCustomerDepart depart = customerDepartMapper.selectById(customerInfo.getDepartId()); // 查询部门

        customerInfo.setProductName(productInfo.getProductName()).setDepartName(depart.getDepartName());
        list.add(customerInfo);
        return list;
    }

    /**
     * 团订获取产品返修尺寸列表
     *
     * @param token 令牌
     * @param code  小产品编码
     * @return 返修尺寸列表
     */
    @Override
    public Set<MlccCategoryFanxiuInfo> listAftersize(String token, String code) {
        if (!fabricUtil.checkToken(token)) return null;
        QueryWrapper<MlccCustomerProductInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("code", code);
        MlccCustomerProductInfo one = smallProductMapper.selectOne(wrapper);
        if (one == null) return null;
        // 获取小产品对应的大产品
        MlccProductInfo productInfo = productInfoMapper.selectById(one.getProductId());
        HashSet<MlccCategoryFanxiuInfo> set = new HashSet<>();
        if (productInfo != null) {
            // 根据产品的品类回去这个产品可以返修的参数
            String PLID = fabricUtil.getpingleiFromProduct(productInfo);
            System.out.println("品类ID：" + PLID);
            if (PLID != null) {
                QueryWrapper<MlccCategoryFanxiuInfo> wrapper2 = new QueryWrapper<>();
                wrapper2.eq("category_id", PLID);
                List<MlccCategoryFanxiuInfo> fanxiuInfos = fanxiuMapper.selectList(wrapper2);
                System.out.println(fanxiuInfos);
                if (fanxiuInfos != null && fanxiuInfos.size() > 0) {
                    fanxiuInfos.stream().forEach(fanxiu -> {
                        fanxiu.setValue("");
                        set.add(fanxiu);
                    });
                }
            }
        }
        return set;
    }

    /**
     * 团订小产品选择重做，查询真正的尺寸表
     *
     * @param token 令牌
     * @param code  小产品编码
     */
    @Override
    public List<MlccXiaoProductBodysize> listBodySize(String token, String code) {
        if (!fabricUtil.checkToken(token)) return null;
        QueryWrapper<MlccCustomerProductInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("code", code);
        MlccCustomerProductInfo one = smallProductMapper.selectOne(wrapper);
        if (one == null) return null;
        // 查询小产品尺寸表
        QueryWrapper<MlccXiaoProductBodysize> smallWrapper = new QueryWrapper<>();
        smallWrapper.eq("customer_product_id", one.getId()).eq("team_order_sn", one.getTeamOrderSn())
                .in("bodysize_id", Arrays.asList(one.getBodySizeIds().split(",")))
                .eq("isfanxiu", 0);
        List<MlccXiaoProductBodysize> bodysizes = xiaoBodysizeMapper.selectList(smallWrapper);
        for (MlccXiaoProductBodysize bodysize : bodysizes) {
            bodysize.setBodySizename(bodySizeMapper.selectById(bodysize.getBodysizeId()).getBodySizename());
        }
        return bodysizes;
    }

    /**
     * 团订新增返修数据（小产品尺寸表添加返修尺寸数据）
     *
     * @param token      令牌
     * @param code       小产品编号
     * @param afterCode  售后订单编号
     * @param img        图片
     * @param list       尺寸参数集合
     * @param fabricList 面料集合
     */
    @Transactional
    @Override
    public int saveAfter(String token, String code, String afterCode, String img, List<MlccCategoryFanxiuInfo> list,
                         List<MlccFabricInfo> fabricList, String reason) {
        if (!fabricUtil.checkToken(token)) return -1;
        // 如果这个小产品之前提交过售后，并且还没有完成之前的售后，那么不可以申请本次售后
        if (smallProisFan(code)) {
            return -2;
        }
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        // 拿到小产品
        QueryWrapper<MlccCustomerProductInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("code", code);
        MlccCustomerProductInfo productInfo = smallProductMapper.selectOne(wrapper);
        for (MlccCategoryFanxiuInfo fanxiuInfo : list) { // 遍历返修参数
            if (fanxiuInfo.getValue() != null && !"".equals(fanxiuInfo.getValue())) {
                // 向派单成本表添加返修记录
                orderService.saveFanxiuChengben(afterCode, productInfo.getProductId(), fanxiuInfo.getId() + "", productInfo.getTeamOrderSn(), fanxiuInfo.getBodySizename(), code);

                QueryWrapper<MlccXiaoProductBodysize> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("team_order_sn", productInfo.getTeamOrderSn())
                        .eq("customer_product_id", productInfo.getId())
                        .eq("bodysize_id", fanxiuInfo.getId()).eq("isfanxiu", 1)
                        .eq("after_order", afterCode);
                MlccXiaoProductBodysize selectOne = xiaoBodysizeMapper.selectOne(wrapper1);
                if (selectOne == null) {
                    MlccXiaoProductBodysize bodysize = new MlccXiaoProductBodysize();
                    // 向小产品尺寸表添加记录
                    bodysize.setTeamOrderSn(productInfo.getTeamOrderSn()).setCustomerProductId(productInfo.getId())
                            .setBodysizeId(fanxiuInfo.getId() + "").setBodysizeValue(fanxiuInfo.getValue()).setCreateBy(userDetail.getUsername())
                            .setUpdateBy(userDetail.getUsername()).setIsfanxiu(1).setAfterOrder(afterCode);
                    int insert = xiaoBodysizeMapper.insert(bodysize);
                } else {
                    // 否则执行更新操作
                    selectOne.setBodysizeValue(fanxiuInfo.getValue());
                    xiaoBodysizeMapper.updateById(selectOne);
                }
                /*if (insert == 0) {
                    return 0;
                }*/
            }
        }
        // 返修不需要面料
        // 拿到修改的面料信息
//        String idAndMishu = "";
//        double fabricPrice = 0;
//        for (MlccFabricInfo fabricInfo : fabricList) {
//            if (fabricInfo.getMishu() != null && !"".equals(fabricInfo.getMishu())) {
//                idAndMishu += fabricInfo.getId() + "/" + fabricInfo.getMishu() + ",";
//                fabricPrice += fabricInfo.getAllPrice();
//            }
//        }
        // 去除最后一个多余的逗号
//        if (!"".equals(idAndMishu)) {
//            idAndMishu = idAndMishu.substring(0, idAndMishu.length() - 1);
//        }
        // 接下来要改变小产品的状态，添加售后单号和售后图片
        productInfo.setIsAfter(1).setAfterCode(afterCode).setUpdateBy(userDetail.getUsername()).setAfterimg(img).setRemark(reason);
//        if (!"".equals(idAndMishu)) {
        productInfo.setAfterAgree(0);
//        }
        return smallProductMapper.updateById(productInfo);
    }

    /**
     * 团订前端选择重做
     *
     * @param token      令牌
     * @param code       小产品编号
     * @param afterCode  售后订单编号
     * @param img        图片
     * @param list       尺寸参数集合
     * @param fabricList 面料集合
     */
    @Override
    public int saveRedo(String token, String code, String afterCode, String img, List<MlccCategoryFanxiuInfo> list, List<MlccFabricInfo> fabricList, String reason) {
        if (!fabricUtil.checkToken(token)) return -1;
        // 如果这个小产品之前提交过售后，并且还没有完成之前的售后，那么不可以申请本次售后
        if (smallProisFan(code)) {
            return -2;
        }
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        // 拿到小产品
        QueryWrapper<MlccCustomerProductInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("code", code);
        MlccCustomerProductInfo productInfo = smallProductMapper.selectOne(wrapper);

        for (MlccCategoryFanxiuInfo fanxiuInfo : list) {
            if (fanxiuInfo.getBodysizeValue() != null && !"".equals(fanxiuInfo.getBodysizeValue())) {
                QueryWrapper<MlccXiaoProductBodysize> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("team_order_sn", productInfo.getTeamOrderSn())
                        .eq("customer_product_id", productInfo.getId())
                        .eq("bodysize_id", fanxiuInfo.getBodysizeId()).eq("isfanxiu", 2)
                        .eq("after_order", afterCode);
                MlccXiaoProductBodysize selectOne = xiaoBodysizeMapper.selectOne(wrapper1);

                if (selectOne == null) {
                    // 重做插入数据是要有条件的，只有当传过来的尺寸和原来的正常尺寸不一样时，才进行插入操作
                    QueryWrapper<MlccXiaoProductBodysize> wrapper2 = new QueryWrapper<>();
                    wrapper2.eq("team_order_sn", productInfo.getTeamOrderSn())
                            .eq("customer_product_id", productInfo.getId())
                            .eq("bodysize_id", fanxiuInfo.getBodysizeId())
                            .eq("isfanxiu", 0).isNull("after_order");
                    MlccXiaoProductBodysize selectAgin = xiaoBodysizeMapper.selectOne(wrapper2);
                    System.out.println("原来的尺寸======" + selectAgin);
                    if (selectAgin != null && !selectAgin.getBodysizeValue().equals(fanxiuInfo.getBodysizeValue())) {
                        System.out.println("************插入了数据************");
                        MlccXiaoProductBodysize bodysize = new MlccXiaoProductBodysize();
                        // 向小产品尺寸表添加记录
                        bodysize.setTeamOrderSn(productInfo.getTeamOrderSn()).setCustomerProductId(productInfo.getId())
                                .setBodysizeId(fanxiuInfo.getBodysizeId() + "").setBodysizeValue(fanxiuInfo.getBodysizeValue()).setCreateBy(userDetail.getUsername())
                                .setUpdateBy(userDetail.getUsername()).setIsfanxiu(2).setAfterOrder(afterCode);
                        int insert = xiaoBodysizeMapper.insert(bodysize);
                    }
                } else {
                    // 否则执行更新操作
                    selectOne.setBodysizeValue(fanxiuInfo.getValue());
                    xiaoBodysizeMapper.updateById(selectOne);
                }

                /*if (insert == 0) {
                    return 0;
                }*/
            }
        }
        // 拿到修改的面料信息
        String idAndMishu = "";
        double fabricPrice = 0;// 面料价格
        for (MlccFabricInfo fabricInfo : fabricList) {
            if (fabricInfo.getMishu() != null && !"".equals(fabricInfo.getMishu())) {
                idAndMishu += fabricInfo.getId() + "/" + fabricInfo.getMishu() + ",";
                fabricPrice += fabricInfo.getAllPrice();
            }
        }
        // 去除最后一个多余的逗号
        if (!"".equals(idAndMishu)) {
            idAndMishu = idAndMishu.substring(0, idAndMishu.length() - 1);
        }
        // 接下来要改变小产品的状态，添加售后单号和售后图片
        productInfo.setIsAfter(2).setAfterCode(afterCode).setUpdateBy(userDetail.getUsername()).setAfterimg(img).setRemark(reason);
        if (!"".equals(idAndMishu)) {
            productInfo.setFabricids(idAndMishu).setAfterAgree(0).setAfterFabricPrice(new BigDecimal(fabricPrice).setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        return smallProductMapper.updateById(productInfo);
    }

    /**
     * 团订获取本次售后的人员列表
     *
     * @param token     令牌
     * @param afterCode 售后订单编号
     * @return 人员列表
     */
    @Override
    public List<MlccCustomerInfo> listAfterEmp(String token, String afterCode) {
        if (!fabricUtil.checkToken(token)) return null;
        QueryWrapper<MlccCustomerProductInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("after_code", afterCode);
        List<MlccCustomerProductInfo> list = smallProductMapper.selectList(wrapper);
        ArrayList<MlccCustomerInfo> customerInfos = new ArrayList<>();
        for (MlccCustomerProductInfo productInfo : list) {
            MlccCustomerInfo mlccCustomerInfo = customeInfoMapper.selectById(productInfo.getCustomerId());
            // 前端要展示部门名称
            mlccCustomerInfo.setDepartName(customerDepartMapper.selectById(mlccCustomerInfo.getDepartId()).getDepartName());
            // 前端展示产品名称
            mlccCustomerInfo.setProductName(productInfoMapper.selectById(productInfo.getProductId()).getProductName());
            // 前端需要展示售后类型
            mlccCustomerInfo.setAfterType(productInfo.getIsAfter());
            customerInfos.add(mlccCustomerInfo);
        }
        return customerInfos;
    }

    /**
     * 根据小产品编码获取小产品ID
     *
     * @param token 令牌
     * @param code  小产品代码
     * @return 小产品数据
     */
    @Override
    public MlccCustomerProductInfo getSmallPro(String token, String code) {
        if (!fabricUtil.checkToken(token)) return null;
        QueryWrapper<MlccCustomerProductInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("code", code);
        return smallProductMapper.selectOne(wrapper);
    }

    /**
     * 获取小产品面料
     *
     * @param token   令牌
     * @param code    小产品编号
     * @param orderSn 订单编号
     */
    @Override
    public List<MlccFabricInfo> getFabricList(String token, String code, String orderSn, Double mishu) {
        if (!fabricUtil.checkToken(token)) return null;
        // 获取订单基本信息
        QueryWrapper<MlccTeamOrderInfo> orderInfoQueryWrapper = new QueryWrapper<>();
        orderInfoQueryWrapper.eq("order_sn", orderSn);
        MlccTeamOrderInfo teamOrderInfo = teamOrderMapper.selectOne(orderInfoQueryWrapper);

        // 拿到小产品
        QueryWrapper<MlccCustomerProductInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("code", code);
        MlccCustomerProductInfo productInfo = smallProductMapper.selectOne(wrapper);
        ArrayList<MlccFabricInfo> fabricInfos = new ArrayList<>();
        if (productInfo != null) {
            // 通过小产品拿到大产品
            MlccProductInfo mlccProductInfo = productInfoMapper.selectById(productInfo.getProductId());
            String fabricIds = mlccProductInfo.getFabricIds(); // 面料ID和米数：格式  id/米数,id/米数
            String[] split = fabricIds.split(",");
            for (String idAndMishu : split) {
                String[] split1 = idAndMishu.split("/");
                MlccFabricInfo fabricInfo = fabricInfoMapper.selectById(split1[0]);
                MlccFabricInfo mlccFabricInfo = fabricUtil.addPrice(fabricInfo, Double.valueOf(split1[1]));
                if (mishu == null) {
                    mishu = Double.valueOf(split1[1]);
                }
                double khzk = 1;
                if (mlccFabricInfo.getGroupId() != null) {
                    // 获取客户折扣
                    khzk = fabricUtil.userFabricDiscount(teamOrderInfo.getUserId(), mlccFabricInfo.getGroupId());
                }
                if (mishu != null) {
                    fabricUtil.addPrice(mlccFabricInfo, mishu);
                    mlccFabricInfo.setMishu(mishu.toString());

                }
                mlccFabricInfo.setKehuzk(khzk);
                // 计算折后单价并赋值
                BigDecimal decimal = mlccFabricInfo.getFabricPrice().multiply(new BigDecimal(Double.valueOf(khzk)));
                mlccFabricInfo.setAfterPrice(decimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

                // 计算总价格
                System.out.println("折后单价===" + mlccFabricInfo.getAfterPrice());
                System.out.println("米数=======" + mishu);
                BigDecimal multiply = new BigDecimal(mlccFabricInfo.getAfterPrice()).multiply(new BigDecimal(mishu));
                // 保留两位小数
                mlccFabricInfo.setAllPrice(multiply.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                fabricInfos.add(mlccFabricInfo);
            }
        }
        return fabricInfos;
    }

    /**
     * 团订售后，计算本次售后的价格
     *
     * @param token     令牌
     * @param afterCode 售后订单编号
     * @param orderSn   团订订单编号
     */
    @Override
    public double checkAfterPrice(String token, String afterCode) {
        if (!fabricUtil.checkToken(token)) return 0;
        double lastPrice = 0;
        // 1、查询本次售后所有的返修参数价格
        QueryWrapper<MlccXiaoProductBodysize> wrapper = new QueryWrapper<>();
        wrapper.eq("after_order", afterCode).eq("isfanxiu", 1);
        List<MlccXiaoProductBodysize> bodysizes = xiaoBodysizeMapper.selectList(wrapper);
        if (bodysizes != null && bodysizes.size() > 0) {
            for (MlccXiaoProductBodysize bodysize : bodysizes) {
                // 拿到小产品
                MlccCustomerProductInfo smallProductInfo = smallProductMapper.selectById(bodysize.getCustomerProductId());
                if (smallProductInfo != null) {
                    // 获取小产品对应的大产品
                    MlccProductInfo productInfo = productInfoMapper.selectById(smallProductInfo.getProductId());
                    if (productInfo != null) {
                        // 获取产品的品类ID
                        String PLID = fabricUtil.getpingleiFromProduct(productInfo);
                        if (PLID != null) {
                            // 确定业务类型
                            QueryWrapper<MlccPriceSystemPinglei> wrapper1 = new QueryWrapper<>();
                            wrapper1.eq("category_id", PLID).eq("business_type", smallProductInfo.getBodysType() == 0 ? 1 : 2);
                            MlccPriceSystemPinglei systemPinglei = priceSystemPingleiMapper.selectOne(wrapper1);
                            if (systemPinglei != null) {
                                QueryWrapper<MlccPriceSystemCostRecord> recordQueryWrapper = new QueryWrapper<>();
                                recordQueryWrapper.eq("cost_item", PLID).eq("cost_id", bodysize.getBodysizeId()).eq("type", 6)
                                        .eq("price_system_id", systemPinglei.getId());
                                MlccPriceSystemCostRecord record = recordMapper.selectOne(recordQueryWrapper);
                                if (record != null) {
                                    lastPrice += record.getPrice().doubleValue();
                                }
                            }
                        }
                    }

                }
            }
        }

        // 2、计算面料的钱
        QueryWrapper<MlccCustomerProductInfo> wrapper1 = new QueryWrapper<>();
        // 只有重做才需要计算面料的钱
        wrapper1.eq("after_code", afterCode).eq("is_after", 2);
        // 查询本次售后的所有小产品
        List<MlccCustomerProductInfo> smallProduceList = smallProductMapper.selectList(wrapper1);
        if (smallProduceList != null && smallProduceList.size() > 0) {
            for (MlccCustomerProductInfo smallPro : smallProduceList) {
                lastPrice += smallPro.getAfterFabricPrice().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            }
        }
        return lastPrice;
    }

    /**
     * 新建售后订单（团订订单售后，点击售后就创建一条）
     *
     * @param orderSn 订单号
     * @param token   令牌
     * @return 返回售后订单编号
     */
    @Override
    public String createAfterOrder(String orderSn, String token) {
        if (!fabricUtil.checkToken(token)) return null;
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        // 查询订单基本信息
        QueryWrapper<MlccTeamOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccTeamOrderInfo teamOrderInfo = teamOrderMapper.selectOne(wrapper);

        // 创建一个随机数
        Random random = new Random();
        int i = random.nextInt(9999);

        // 创建一条售后订单记录 (未启用状态)
        MlccAfterSalesinfo salesinfo = new MlccAfterSalesinfo();
        String afterCode = System.currentTimeMillis() + "" + i;
//        String uuid = UUID.randomUUID().toString();
        salesinfo.setAfterCode(afterCode).setUserId(userDetail.getId() + "").setOrderId(teamOrderInfo.getId() + "")
                .setAfterSalesType(2)
                .setOrdertype(2).setOrderSn(teamOrderInfo.getOrderSn()).setStoreId(teamOrderInfo.getStoreId()).setStatus(1);
        int insert = afterSalesinfoMapper.insert(salesinfo);
        if (insert > 0) {
            return afterCode;
        } else {
            return null;
        }
    }

    /**
     * 团订我的订单——统计本次售后的金额
     *
     * @param token
     * @param afterOrder
     */
    @Override
    public double getAfterPrice(String token, String afterOrder, String orderSn) {
        if (!fabricUtil.checkToken(token)) return -1;
        double totalMoney = 0;
        double khzk = fabricUtil.getkhzktd(orderSn);

        // 1、查询售后订单金额
        QueryWrapper<MlccXiaoProductBodysize> wrapper = new QueryWrapper<>();
        wrapper.eq("after_order", afterOrder).in("isfanxiu", 1, 2);
        List<MlccXiaoProductBodysize> list = xiaoBodysizeMapper.selectList(wrapper);
        for (MlccXiaoProductBodysize productBodysize : list) {
            // 返修和售后的金额分开统计
            /*先统计返修金额*/
            if (productBodysize.getIsfanxiu() == 1) {
                MlccCategoryFanxiuInfo fanxiuInfo = fanxiuMapper.selectById(productBodysize.getId());
                if (fanxiuInfo != null && fanxiuInfo.getTeamPrice2() != null) {
                    totalMoney += Double.valueOf(fanxiuInfo.getTeamPrice2());
                }
            } else if (productBodysize.getIsfanxiu() == 2) {
                // 如果是重做，价格就是产品的价格
                MlccCustomerProductInfo customerProductInfo = smallProductMapper.selectById(productBodysize.getCustomerProductId());
                MlccProductInfo productInfo = productInfoMapper.selectById(customerProductInfo.getProductId());
                totalMoney += productInfo.getZhehouPrice().doubleValue();
            }
        }
        // 接下来查询面料价格
        QueryWrapper<MlccCustomerProductInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("after_code", afterOrder);
        List<MlccCustomerProductInfo> productInfoList = smallProductMapper.selectList(queryWrapper);
        for (MlccCustomerProductInfo customerProductInfo : productInfoList) {
            String fabricids = customerProductInfo.getFabricids();
            String[] idAndMishus = fabricids.split(","); // 获取这个小产品的面料数据：id/米数
            for (String fabricid : idAndMishus) {
                String[] split = fabricid.split("/");
                MlccFabricInfo fabricInfo = fabricInfoMapper.selectById(split[0]);
                MlccFabricInfo info = fabricUtil.addPrice(fabricInfo, Double.valueOf(split[1])); // 拿到了面料价格
                totalMoney += (info.getFabricPrice().doubleValue() * Double.valueOf(split[1]) * khzk);
            }
        }
        return totalMoney;
    }

    /**
     * 更新团订订单   团订售后支付
     *
     * @param token     令牌
     * @param orderSn   订单编号
     * @param afterCode 售后订单编号
     * @param money     本次售后价格
     */
    @Override
    public int updateTeamOrder(String token, String orderSn, String afterCode, String money, String reason) {
        if (!fabricUtil.checkToken(token)) return -1;
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        // 查询售后订单基本信息
        QueryWrapper<MlccAfterSalesinfo> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("after_code", afterCode);
        MlccAfterSalesinfo afterSalesinfo = afterSalesinfoMapper.selectOne(wrapper1);
        // 售后订单支付
        int payResult = fabricUtil.payAfterOrder(new BigDecimal(Double.valueOf(money)), token, afterSalesinfo);
        if (payResult > 0) {
            System.out.println("支付成功！！！");
            // 事件表插入数据
            inserEvent(2, 1, "团订订单申请售后", 2, afterSalesinfo.getId() + "", afterSalesinfo.getAfterCode());
            // 向异常订单添加一条数据
            MlccErrorOrder errorOrder = new MlccErrorOrder();
            errorOrder.setId(UUID.randomUUID().toString()).setErrorName("售后订单")
                    .setOrderSn(orderSn).setOrderType(2);
            errorOrderMapper.insert(errorOrder);

            QueryWrapper<MlccTeamOrderInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("order_sn", orderSn);
            MlccTeamOrderInfo one = teamOrderMapper.selectOne(wrapper);
            one.setUpdateBy(userDetail.getUsername()).setStatus(9);
            int updateById = teamOrderMapper.updateById(one);
            // 添加订单跟踪记录
            MlccTrackingOrder trackingOrder = new MlccTrackingOrder();
            trackingOrder.setOrderSn(orderSn).setOrderType(2).setRemark("团订售后").setThing("申请售后")
                    .setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername());
            int insert = trackingOrderMapper.insert(trackingOrder);
            if (updateById > 0 && insert > 0) {
                // 啊啊啊！要启用返修的成本啊！！！(等后台同意了再启用)
                //orderService.takeonFanxiuChengben(orderSn, afterCode);

                // 启用团订的售后订单记录
                if (afterSalesinfo != null) {
                    afterSalesinfo.setStatus(0).setAfterPrice(money).setRemark(reason).setReason(reason).setSysOrgCode(userDetail.getOrgCode());
                    afterSalesinfoMapper.updateById(afterSalesinfo);

                    // 接下来向订单流水表插入数据
                    MlccBusinessWaterInfo waterInfo = new MlccBusinessWaterInfo();
                    waterInfo.setId(UUID.randomUUID().toString()).setType(2).setUserId(userDetail.getId() + "")
                            .setCostMoney(money).setYewuInstructions("售后订单").setYewuDeatil("团订售后支付金额").setStatus(2)
                            .setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername()).setOrderSn(orderSn)
                            .setStoreId(one.getStoreId() + "")
                            .setApplyMethod(3).setAfterOrderSn(afterCode).setIsAfter(1).setSysOrgCode(userDetail.getOrgCode());
                    businessWaterInfoMapper.insert(waterInfo);
                }
                return 1;
            } else {
                return 0;
            }
        }
        return payResult;
    }

    /**
     * 团订获取人员尺寸
     *
     * @param proID
     */
    @Override
    public List<MlccXiaoProductBodysize> listSmallSize(String proID, String orderSn) {
        QueryWrapper<MlccXiaoProductBodysize> wrapper = new QueryWrapper<>();
        wrapper.eq("customer_product_id", proID).eq("isfanxiu", 0).eq("team_order_sn", orderSn);
        List<MlccXiaoProductBodysize> list = xiaoBodysizeMapper.selectList(wrapper);
        for (MlccXiaoProductBodysize bodysize : list) {
            MlccBodySizeInfo sizeInfo = bodySizeMapper.selectById(bodysize.getBodysizeId());
            bodysize.setBodySizename(sizeInfo.getBodySizename()).setUnit(sizeInfo.getUnit());
        }
        return list;
    }

    /**
     * 团订个人尺寸详情，获取类别
     *
     * @param proID 小产品ID
     */
    @Override
    public MlccProductInfo getProName(String proID) {
        MlccCustomerProductInfo info = smallProductMapper.selectById(proID);
        MlccProductInfo info1 = productInfoMapper.selectById(info.getProductId());
        String liangtiImgs = info.getLiangtiImgs();
        if (liangtiImgs != null && !"".equals(liangtiImgs)) {
            String[] split = liangtiImgs.split(",");
            List<String> strings = Arrays.asList(split);
            info1.setImgs(strings);
        }
        info1.setStandardSize(info.getStandardSize()).setLiangtiRemark(info.getLiangtiRemark());
        return info1;

    }

    /**
     * 查询团订订单批次
     *
     * @param token   令牌
     * @param orderSn 团订订单编号
     * @return 批次列表
     */
    @Override
    public List<MlccTrackingTeamDepart> listTrackingteam(String token, String orderSn) {
        if (!fabricUtil.checkToken(token)) return null;
        QueryWrapper<MlccTrackingTeamDepart> wrapper = new QueryWrapper<>();
        wrapper.eq("team_order_sn", orderSn);
        List<MlccTrackingTeamDepart> trackingTeamDeparts = trackingTeamDepartMapper.selectList(wrapper);
        if (trackingTeamDeparts != null && trackingTeamDeparts.size() > 0) {
            for (MlccTrackingTeamDepart teamDepart : trackingTeamDeparts) {
                QueryWrapper<MlccBatchPackingInfo> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("batch_id", teamDepart.getId());
                teamDepart.setBatchPackingInfoList(batchPackingInfoMapper.selectList(wrapper1))
                        .setDepart(customerDepartMapper.selectById(teamDepart.getDepartId()));
            }
        }
        return trackingTeamDeparts;
    }

    /**
     * 团订未发货人员名单
     *
     * @param token   令牌
     * @param orderSn 订单编号
     * @return 小产品列表
     */
    @Override
    public List<MyNotshipmentsEmp> listNotshipments(String token, String orderSn) {
        if (!fabricUtil.checkToken(token)) return null;
        return teamOrderAafterTMapper.listNotshipments(orderSn);
    }

    /**
     * 团订查看已发货人员列表
     *
     * @param token 令牌
     * @param boxID 装箱单ID
     */
    @Override
    public List<MyNotshipmentsEmp> getoutPerson(String token, String boxID) {
        if (!fabricUtil.checkToken(token)) return null;
        return teamOrderAafterTMapper.getoutPerson(boxID);
    }

    /**
     * 获取10个面料数据
     *
     * @param token 令牌
     * @return 面料列表
     */
    @Override
    public List<MlccFabricInfo> listTenFabric(String token, String code) {
        if (!fabricUtil.checkToken(token)) return null;
        return teamOrderAafterTMapper.listTenFabric(code);
    }

    /**
     * 团订产品添加到部门
     *
     * @param entity 前端提交的产品数据
     */
    @Override
    public int addProductDepart(PengProductEntity entity) {
        if (!fabricUtil.checkToken(entity.getToken())) return -1;
        MlccUserInfo userDetail = fabricUtil.getUserDetail(entity.getToken());
        // 判断产品是否添加过
        QueryWrapper<MlccDepartProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customer_depart_id", entity.getCustomerDepartId()).eq("product_id", entity.getProductId());
        List<MlccDepartProduct> mlccDepartProduct = departProductMapper.selectList(queryWrapper);
        System.out.println(mlccDepartProduct);
        if (mlccDepartProduct.size() > 0) {
            return -2;
        }
        MlccProductInfo productInfo = productInfoMapper.selectById(entity.getProductId()); // 选中的产品
        if (entity.getFabricId() != null && !"".equals(entity.getFabricId())) {
            productInfo.setId(UUID.randomUUID().toString()).setFabricIds(entity.getFabricId() + "/" + entity.getNumbers())
                    .setRemark(entity.getRemark()).setXiuziOneNeirong(entity.getXiuziOneNeirong()).setXiuziType(entity.getXiuziType())
                    .setXiuziTwoNeirong(entity.getXiuziTwoNeirong()).setXiuziWeizhi(entity.getXiuziWeizhi())
                    .setXiuziColor(entity.getXiuziColor()).setXiuziZiti(entity.getXiuziZiti()).setNumbers(1)
                    .setProductType(0).setProductName(entity.getProName()).setRemark(entity.getRemark());
            // 新增一条产品记录
            productInfoMapper.insert(productInfo);

            // 部门产品关联表添加记录
            MlccDepartProduct departProduct = new MlccDepartProduct();
            departProduct.setProductId(productInfo.getId()).setCustomerDepartId(entity.getCustomerDepartId())
                    .setRemark(entity.getRemark()).setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername())
                    .setNumbers(entity.getNumbers());
            return departProductMapper.insert(departProduct);
        } else {
            // 部门产品关联表添加记录
            MlccDepartProduct departProduct = new MlccDepartProduct();
            departProduct.setProductId(productInfo.getId()).setCustomerDepartId(entity.getCustomerDepartId())
                    .setRemark(entity.getRemark()).setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername())
                    .setNumbers(entity.getNumbers());
            return departProductMapper.insert(departProduct);
        }
    }

    /**
     * 获取产品基本信息
     *
     * @param proID
     */
    @Override
    public MlccProductInfo getBaseProductDetail(String proID) {
        return productInfoMapper.selectById(proID);
    }

    /**
     * 根据团订订单中的客户ID获取部门信息
     *
     * @param token 令牌
     * @param cuID  团订订单中的客户ID
     */
    @Override
    public MlccCustomerInfo getDepartByCuID(String token, String cuID) {
        if (!fabricUtil.checkToken(token)) return null;
        return customeInfoMapper.selectById(cuID);
    }

    /**
     * 团订模板详情
     *
     * @param moduleSn 模板编号
     * @param token    令牌
     */
    @Override
    public MlccTeamModuleInfo getTeamModuleDetail(String moduleSn, String token) {
        if (!fabricUtil.checkToken(token)) return null;
        return moduleDetail(moduleSn);
    }

    /**
     * 产品基本信息（为了获取类别ID）
     *
     * @param id 产品ID
     */
    @Override
    public MlccProductInfo proDetail(String id) {
        return productInfoMapper.selectById(id);
    }

    /**
     * 计算团订价格
     *
     * @param orderSn 订单编号
     */
    @Override
    public JSONObject teamOrderPrice(String orderSn) {
        QueryWrapper<MlccTeamOrderInfo> teamOrderInfoQueryWrapper = new QueryWrapper<>();
        teamOrderInfoQueryWrapper.eq("order_sn", orderSn);
        // 订单基本信息
        MlccTeamOrderInfo teamOrderInfo = teamOrderMapper.selectOne(teamOrderInfoQueryWrapper);
        // 用户基本信息
        MlccUserInfo mlccUserInfo = userInfoMapper.selectById(teamOrderInfo.getUserId());

        // 查询公司信息
        QueryWrapper<MlccCompanyInfo> cwrapper = new QueryWrapper<>();
        cwrapper.eq("company_code", mlccUserInfo.getCompanyOrgcode());
        MlccCompanyInfo companyInfo = companyInfoMapper.selectOne(cwrapper);
        // 根据公司数据找到公司账号
        MlccUserInfo companyUser = userInfoMapper.selectById(companyInfo.getUserId());
        if (companyUser == null) {
            throw new RuntimeException("公司账号不存在");
        } else {
            mlccUserInfo = companyUser;
        }

        JSONObject jsonObject = new JSONObject();
        BigDecimal allMpney = new BigDecimal(0); // 总价
        // 用来存放订单下的标准码大产品
        ArrayList<MyteamPriceProduct> bzmpro = new ArrayList<>();
        // 用来存放订单下的团订尺码大产品
        ArrayList<MyteamPriceProduct> zdypro = new ArrayList<>();

        double lastPrice = 0;
        // 1、查询订单下的小产品并且进行分组
        List<MyteamPriceProduct> products = teamOrderAafterTMapper.listpriceProduuct(orderSn);
        if (products != null && products.size() > 0) {
            for (MyteamPriceProduct product : products) {
                System.out.println("+++++++++大循环开始+++++++++");
                // 里布价格
                BigDecimal libuPrice = new BigDecimal(0);
                // 低领尼价格
                BigDecimal dilinniPrice = new BigDecimal(0);
                // 纽扣价格
                BigDecimal buttonPrice = new BigDecimal(0);
                // 查到这个大产品的基本信息
                MlccProductInfo productInfo = productInfoMapper.selectById(product.getProductId());
                // 需要判断是现货？？？等待设计明确。。。。。
                String plid = fabricUtil.getpingleiFromProduct(productInfo);
                MlccCategoryInfo PL = categoryInfoMapper.selectById(plid);
                System.out.println("品类=====" + PL);

                if (productInfo != null) {
                    // 计算里布的价格
                    if (productInfo.getLibuId() != null) {
                        MlccMaterialLibuInfo libuInfo = libuInfoMapper.selectById(productInfo.getLibuId());
                        if (libuInfo != null && libuInfo.getSalesPrice() != null) {
                            libuPrice = libuInfo.getSalesPrice();
                            System.out.println("里布的钱====" + libuPrice);
                        }
                    }

                    // 计算低领尼的价格
                    if (productInfo.getDilinliId() != null) {
                        MlccDilinniInfo dilinniInfo = dilinniInfoMapper.selectById(productInfo.getDilinliId());
                        if (dilinniInfo != null && dilinniInfo.getSalesPrice() != null) {
                            dilinniPrice = dilinniInfo.getSalesPrice();
                            System.out.println("低领尼的钱====" + dilinniPrice);
                        }
                    }

                    // 计算纽扣的钱
                    if (productInfo.getButtonsIds() != null) {
                        MlccButtonsInfo buttonsInfo = buttonsInfoMapper.selectById(productInfo.getButtonsIds());
                        if (buttonsInfo != null && buttonsInfo.getRetailPrice() != null) {
                            buttonPrice = buttonsInfo.getRetailPrice();
                            System.out.println("纽扣====" + buttonPrice);
                        }
                    }

                    // 获取产品的工艺类型ID
                    String gylx = fabricUtil.getGYLXFromProduct(productInfo);
                    System.out.println("工艺类型id===" + gylx);
                    // 工艺类型的id查到的是展示用的，与实际设置了价格的有区别
                    // 这是原来的工艺类型对象，没有设置折扣
                    MlccCategoryInfo categoryInfo = categoryInfoMapper.selectById(gylx);
                    /*注意：需要重新定位到真正的工艺id，此时查到的是前端展示，与设置折扣的工艺不是同一个，但是编号相同*/
                    QueryWrapper<MlccCategoryInfo> wrapper11 = new QueryWrapper<>();
                    wrapper11.eq("category_code", categoryInfo.getCategoryCode()).eq("topid", plid)
                            .eq("is_type", 4).eq("status", 0);
                    // 这是查询到了设置了折扣的工艺
                    MlccCategoryInfo newCategoryInfo = categoryInfoMapper.selectOne(wrapper11);
                    if (newCategoryInfo != null) {
                        categoryInfo = newCategoryInfo;
                    }


                    // 查询这个产品下的标准码尺寸 小产品数量
                    QueryWrapper<MlccCustomerProductInfo> bzmWrapper = new QueryWrapper<>();
                    bzmWrapper.eq("team_order_sn", orderSn).eq("product_id", product.getId())
                            .eq("is_after", 0).eq("bodys_type", 1);
                    int bzmcount = smallProductMapper.selectCount(bzmWrapper);
                    System.out.println("标准码数量" + bzmcount);

                    // 查询这个产品下的团订尺寸 小产品数量
                    QueryWrapper<MlccCustomerProductInfo> tdWrapper = new QueryWrapper<>();
                    tdWrapper.eq("team_order_sn", orderSn).eq("product_id", product.getId())
                            .eq("is_after", 0).eq("bodys_type", 0);
                    int tdmcount = smallProductMapper.selectCount(tdWrapper);
                    System.out.println("团订数量" + tdmcount);
                    // 这个产品的标准吗尺寸是多少？
                    if (gylx != null) {
                        if (bzmcount > 0) {
                            double zk = 1;
                            // 阶梯价
                            BigDecimal price = new BigDecimal(0);
                            // 确定价格体系
                            QueryWrapper<MlccPriceSystemPinglei> wrapper = new QueryWrapper<>();
                            wrapper.eq("category_id", categoryInfo.getId()).eq("business_type", 2).eq("is_gongyi", 1);
                            MlccPriceSystemPinglei systemPinglei = priceSystemPingleiMapper.selectOne(wrapper);
                            if (systemPinglei != null) {
                                // 确定工艺折扣
                                QueryWrapper<MlccDiscountPricesystem> pricesysytemQueryWrapper = new QueryWrapper<>();
                                pricesysytemQueryWrapper.eq("discount_type_id", mlccUserInfo.getDiscount())
                                        .eq("price_system_id", systemPinglei.getId());
                                MlccDiscountPricesystem mlccDiscountPricesysytem = discountPricesysytemMapper.selectOne(pricesysytemQueryWrapper);
                                if (mlccDiscountPricesysytem != null) {
                                    zk = Double.valueOf(mlccDiscountPricesysytem.getDiscountRatio());
                                }
                                // 确定价格区间
                                QueryWrapper<MlccPriceSystemInterval> wrapper1 = new QueryWrapper<>();
                                System.out.println("价格体系id====" + systemPinglei.getId());
                                System.out.println("产品数量====" + bzmcount);
                                wrapper1.eq("price_system_id", systemPinglei.getId()).ne("status", 2);
                                List<MlccPriceSystemInterval> intervals = priceIntervalMapper.selectList(wrapper1);
                                if (intervals != null && intervals.size() > 0) {
                                    for (MlccPriceSystemInterval interval : intervals) {
                                        if (bzmcount >= interval.getMinNumbers() && bzmcount < interval.getMaxNumbers()) {
                                            System.out.println("价格区间是多少？？？？" + interval);
                                            if (interval != null) {
                                                // 拿到了价格
                                                price = interval.getPrice();
                                            }
                                        }
                                    }
                                }
                            }
                            MyteamPriceProduct result1 = new MyteamPriceProduct();
                            if (PL != null) {
                                result1.setPingleiName(PL.getCategoryName());
                            }
                            result1.setId(product.getId()).setProductId(product.getProductId()).setNum(bzmcount)
                                    .setProductName(productInfo.getProductName()).setZk(zk)
                                    .setZheqianPrice(price.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue())
                                    .setZhehouPrice(price.multiply(new BigDecimal(zk)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue())
                                    .setSex(product.getSex())
                                    .setSinglePrice(price.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "")
                                    .setPrice(price.multiply(new BigDecimal(bzmcount)).multiply(new BigDecimal(zk)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());

                            allMpney = allMpney.add((price.multiply(new BigDecimal(bzmcount)).multiply(new BigDecimal(zk))));
                            allMpney = allMpney.add(libuPrice.multiply(new BigDecimal(bzmcount))); // 加上里布的钱
                            allMpney = allMpney.add(dilinniPrice.multiply(new BigDecimal(bzmcount))); // 加上低领尼的钱
                            allMpney = allMpney.add(buttonPrice.multiply(new BigDecimal(bzmcount))); // 加上纽扣的钱
                            bzmpro.add(result1);

                        }

                        System.out.println("==================下面是团订=================");
                        // 这里是团订的价格
                        if (tdmcount > 0) {
                            double zk = 1; // 当作折扣
                            BigDecimal price = new BigDecimal(0);
                            // 确定价格体系
                            QueryWrapper<MlccPriceSystemPinglei> wrapper = new QueryWrapper<>();
                            wrapper.eq("category_id", categoryInfo.getId()).eq("business_type", 1).eq("is_gongyi", 1);
                            MlccPriceSystemPinglei systemPinglei = priceSystemPingleiMapper.selectOne(wrapper);
                            if (systemPinglei != null) {
                                // 确定工艺折扣
                                QueryWrapper<MlccDiscountPricesystem> pricesysytemQueryWrapper = new QueryWrapper<>();
                                pricesysytemQueryWrapper.eq("discount_type_id", mlccUserInfo.getDiscount())
                                        .eq("price_system_id", systemPinglei.getId());
                                MlccDiscountPricesystem mlccDiscountPricesysytem = discountPricesysytemMapper.selectOne(pricesysytemQueryWrapper);
                                if (mlccDiscountPricesysytem != null) {
                                    zk = Double.valueOf(mlccDiscountPricesysytem.getDiscountRatio());
                                }

                                // 确定价格区间
                                QueryWrapper<MlccPriceSystemInterval> wrapper1 = new QueryWrapper<>();
                                wrapper1.eq("price_system_id", systemPinglei.getId()).ne("status", 2);
                                List<MlccPriceSystemInterval> intervals = priceIntervalMapper.selectList(wrapper1);
                                if (intervals != null && intervals.size() > 0) {
                                    for (MlccPriceSystemInterval interval : intervals) {
                                        if (tdmcount >= interval.getMinNumbers() && tdmcount < interval.getMaxNumbers()) {
                                            System.out.println("价格区间是多少？？？？" + interval);
                                            if (interval != null) {
                                                // 拿到了价格
                                                price = interval.getPrice();
                                            }
                                        }
                                    }
                                }
                            }
                            MyteamPriceProduct result1 = new MyteamPriceProduct();
                            if (PL != null) {
                                result1.setPingleiName(PL.getCategoryName());
                            }
                            result1.setId(product.getId()).setProductId(product.getProductId()).setNum(tdmcount)
                                    .setProductName(productInfo.getProductName()).setZk(zk)
                                    .setZheqianPrice(price.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue())
                                    .setZhehouPrice(price.multiply(new BigDecimal(zk)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue())
                                    .setSex(product.getSex())
                                    .setSinglePrice(price.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "")
                                    .setPrice(price.multiply(new BigDecimal(tdmcount)).multiply(new BigDecimal(zk)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                            allMpney = allMpney.add(price.multiply(new BigDecimal(tdmcount)).multiply(new BigDecimal(zk)));
                            allMpney = allMpney.add(libuPrice.multiply(new BigDecimal(tdmcount))); // 加上里布的钱
                            allMpney = allMpney.add(dilinniPrice.multiply(new BigDecimal(tdmcount))); // 加上低领尼的钱
                            allMpney = allMpney.add(buttonPrice.multiply(new BigDecimal(tdmcount))); // 加上纽扣的钱
                            zdypro.add(result1);
                        }
                    }
                }
            }
        }
        jsonObject.put("code", 0);
        jsonObject.put("bzm", bzmpro);
        jsonObject.put("zdy", zdypro);
        jsonObject.put("allMpney", allMpney.setScale(2, BigDecimal.ROUND_HALF_UP));
        return jsonObject;
    }


    /**
     * 团订查询成本价（加价服务）
     *
     * @param orderSn 团订订单编号
     */
    @Override
    public JSONObject teamOrderChengben(String orderSn) {
        JSONObject jsonObject = new JSONObject();
        // 用来计算所有加价项目的价格总和
        Double allMoney = 0.0;
        // 1、查询订单下的小产品并且进行分组
        List<MyteamPriceProduct> myproducts = teamOrderAafterTMapper.listpriceProduuct(orderSn);
        /*// 用来存放订单下的所有大产品
        ArrayList<MlccProductInfo> productInfos = new ArrayList<>();*/
        // 用来存放最后的结果
        ArrayList<MlccPriceSystemCostRecord> result = new ArrayList<>();

        if (myproducts != null && myproducts.size() > 0) {
            for (MyteamPriceProduct myproduct : myproducts) {
                MlccProductInfo productInfo = productInfoMapper.selectById(myproduct.getProductId());

                // 查询这个产品下的标准码尺寸 小产品数量
                QueryWrapper<MlccCustomerProductInfo> bzmWrapper = new QueryWrapper<>();
                bzmWrapper.eq("team_order_sn", orderSn).eq("product_id", productInfo.getId())
                        .eq("bodys_type", 1);
                int bzmcount = smallProductMapper.selectCount(bzmWrapper);
                System.out.println("标准码数量" + bzmcount);

                // 查询这个产品下的团订尺寸 小产品数量
                QueryWrapper<MlccCustomerProductInfo> tdWrapper = new QueryWrapper<>();
                tdWrapper.eq("team_order_sn", orderSn).eq("product_id", productInfo.getId())
                        .eq("bodys_type", 0);
                int tdmcount = smallProductMapper.selectCount(tdWrapper);
                System.out.println("团订数量" + tdmcount);

                // 1、大产品下的标准码数量---------------------------------------------
                if (bzmcount > 0) {
                    // 1、获取这个产品的品类
                    String PLID = fabricUtil.getpingleiFromProduct(productInfo);
                    // 获取品类名称
                    MlccCategoryInfo plinfo = categoryInfoMapper.selectById(PLID);
                    // 2、查询产品名下的定制项参数
                    List<String> dzxList = fabricUtil.getDDZXFromProduct(productInfo);
                    // 定制项的编号集合
                    List<String> dzxCode = fabricUtil.dzxCode(dzxList);
                    // 根据品类和业务类型确定价格体系
                    QueryWrapper<MlccPriceSystemPinglei> wrapper1 = new QueryWrapper<>();
                    wrapper1.eq("category_id", PLID).eq("business_type", 2).eq("is_gongyi", 0);
                    MlccPriceSystemPinglei pinglei = priceSystemPingleiMapper.selectOne(wrapper1);
                    if (pinglei != null) {
                        // 1、查询产品定制下的参数的价格
                        if (dzxList != null && dzxList.size() > 0) {
                            QueryWrapper<MlccPriceSystemCostRecord> wrapper2 = new QueryWrapper<>();
                            wrapper2.eq("price_system_id", pinglei.getId()).eq("cost_item", PLID).in("cost_code", dzxCode)
                                    .eq("type", 1);
                            List<MlccPriceSystemCostRecord> dsxrecords = recordMapper.selectList(wrapper2);
                            if (dsxrecords != null && dsxrecords.size() > 0) {
                                for (MlccPriceSystemCostRecord dsxrecord : dsxrecords) {
                                    // 总的钱
                                    BigDecimal multiply = dsxrecord.getPrice().multiply(new BigDecimal(bzmcount));
                                    System.out.println("bzm定制项总的钱：" + multiply.toString());
                                    allMoney += multiply.doubleValue();
                                    // 设置基本信息
                                    dsxrecord.setNumber(bzmcount).setPrice(multiply).setButype(2)
                                            .setProductName(plinfo.getCategoryName());
                                    result.add(dsxrecord);
                                }
                            }
                        }

                        // 2、查询这个产品撞色的加价
                        String zhuangseIds = productInfo.getZhuangseIds();
                        if (zhuangseIds != null && !"".equals(zhuangseIds)) {
                            String[] split = zhuangseIds.split(",");
                            if (split != null && split.length > 0) {
                                for (String idAandColor : split) {
                                    // 拿到每个撞色ID
                                    String[] array = idAandColor.split("/");
                                    QueryWrapper<MlccPriceSystemCostRecord> wrapper2 = new QueryWrapper<>();
                                    MlccContrastcolorInfo contrastcolorInfo = contrastColorMapper.selectById(array[0]);
                                    wrapper2.eq("price_system_id", pinglei.getId()).eq("cost_item", PLID)
                                            .eq("type", 3);
                                    if (contrastcolorInfo != null) {
                                        wrapper2.eq("cost_code", contrastcolorInfo.getCode());
                                    }
                                    MlccPriceSystemCostRecord colorRecord = recordMapper.selectOne(wrapper2);
                                    if (colorRecord != null) {
                                        colorRecord.setProductName(plinfo.getCategoryName());
                                        BigDecimal multiply = colorRecord.getPrice().multiply(new BigDecimal(bzmcount));
                                        System.out.println("bzm撞色总的钱：" + multiply.toString());
                                        colorRecord.setPrice(multiply);
                                        allMoney += multiply.doubleValue();
                                        colorRecord.setNumber(bzmcount).setButype(2);
                                        result.add(colorRecord);
                                    }
                                }
                            }
                        }

                        // 3、查询绣字类型的加价 分为：文字、图片、自定义图片三种价格
                        String xiuziWeizhi = productInfo.getXiuziType();
                        if (xiuziWeizhi != null && !"".equals(xiuziWeizhi)) {
                            QueryWrapper<MlccPriceSystemCostRecord> wrapper2 = new QueryWrapper<>();
                            wrapper2.eq("price_system_id", pinglei.getId()).eq("cost_item", PLID)
                                    .eq("type", 2);
                            MlccPriceSystemCostRecord fontLocationRecord = recordMapper.selectOne(wrapper2);
                            if (fontLocationRecord != null) {
                                fontLocationRecord.setProductName(plinfo.getCategoryName());
                                BigDecimal multiply = fontLocationRecord.getPrice().multiply(new BigDecimal(bzmcount));
                                System.out.println("bzm绣字总的钱：" + multiply.toString());
                                fontLocationRecord.setPrice(multiply);
                                allMoney += multiply.doubleValue();
                                fontLocationRecord.setNumber(bzmcount).setButype(2);
                                result.add(fontLocationRecord);
                            }
                        }
                    }
                }

                // 团订的数量进行计算--------------------------------------------------
                if (tdmcount > 0) {
                    // 1、获取这个产品的品类
                    String PLID = fabricUtil.getpingleiFromProduct(productInfo);
                    // 获取品类名称
                    MlccCategoryInfo plinfo = categoryInfoMapper.selectById(PLID);
                    // 2、查询产品名下的定制项参数
                    List<String> dzxList = fabricUtil.getDDZXFromProduct(productInfo);
                    // 定制项的编号集合
                    List<String> dzxcodes = fabricUtil.dzxCode(dzxList);
                    // 根据品类和业务类型确定价格体系
                    QueryWrapper<MlccPriceSystemPinglei> wrapper1 = new QueryWrapper<>();
                    wrapper1.eq("category_id", PLID).eq("business_type", 1).eq("is_gongyi", 0);
                    MlccPriceSystemPinglei pinglei = priceSystemPingleiMapper.selectOne(wrapper1);
                    if (pinglei != null) {
                        // 1、查询产品定制下的参数的价格
                        if (dzxList != null && dzxList.size() > 0) {
                            QueryWrapper<MlccPriceSystemCostRecord> wrapper2 = new QueryWrapper<>();
                            wrapper2.eq("price_system_id", pinglei.getId()).eq("cost_item", PLID).in("cost_code", dzxcodes)
                                    .eq("type", 1);
                            List<MlccPriceSystemCostRecord> dsxrecords = recordMapper.selectList(wrapper2);
                            if (dsxrecords != null && dsxrecords.size() > 0) {
                                for (MlccPriceSystemCostRecord dsxrecord : dsxrecords) {
                                    dsxrecord.setProductName(plinfo.getCategoryName());
                                    BigDecimal multiply = dsxrecord.getPrice().multiply(new BigDecimal(tdmcount));
                                    System.out.println("td定制项总的钱：" + multiply.toString());
                                    dsxrecord.setPrice(multiply);
                                    allMoney += multiply.doubleValue();
                                    dsxrecord.setNumber(tdmcount).setButype(1);
                                    result.add(dsxrecord);
                                }
                            }
                        }

                        // 2、查询这个产品撞色的加价
                        String zhuangseIds = productInfo.getZhuangseIds();
                        if (zhuangseIds != null) {
                            String[] split = zhuangseIds.split(",");
                            if (split != null && split.length > 0) {
                                for (String idAandColor : split) {
                                    // 拿到每个撞色ID
                                    String[] array = idAandColor.split("/");
                                    QueryWrapper<MlccPriceSystemCostRecord> wrapper2 = new QueryWrapper<>();
                                    MlccContrastcolorInfo contrastcolorInfo = contrastColorMapper.selectById(array[0]);
                                    wrapper2.eq("price_system_id", pinglei.getId()).eq("cost_item", PLID)
                                            .eq("type", 3);
                                    if (contrastcolorInfo != null) {
                                        wrapper2.eq("cost_code", contrastcolorInfo.getCode());
                                    }
                                    MlccPriceSystemCostRecord colorRecord = recordMapper.selectOne(wrapper2);
                                    if (colorRecord != null) {
                                        colorRecord.setProductName(plinfo.getCategoryName());
                                        BigDecimal multiply = colorRecord.getPrice().multiply(new BigDecimal(tdmcount));
                                        System.out.println("td撞色总的钱：" + multiply.toString());
                                        colorRecord.setPrice(multiply);
                                        allMoney += multiply.doubleValue();
                                        colorRecord.setNumber(tdmcount).setButype(1);
                                        result.add(colorRecord);
                                    }
                                }
                            }
                        }

                        // 3、查询绣字类型的加价 分为：文字、图片、自定义图片三种价格
                        String xiuziWeizhi = productInfo.getXiuziType();
                        if (xiuziWeizhi != null && !"".equals(xiuziWeizhi)) {
                            QueryWrapper<MlccPriceSystemCostRecord> wrapper2 = new QueryWrapper<>();
                            wrapper2.eq("price_system_id", pinglei.getId()).eq("cost_item", PLID)
                                    .eq("type", 2);
                            MlccPriceSystemCostRecord fontLocationRecord = recordMapper.selectOne(wrapper2);
                            if (fontLocationRecord != null) {
                                fontLocationRecord.setProductName(plinfo.getCategoryName());
                                BigDecimal multiply = fontLocationRecord.getPrice().multiply(new BigDecimal(tdmcount));
                                System.out.println("td绣字总的钱：" + multiply.toString());
                                fontLocationRecord.setPrice(multiply);
                                allMoney += multiply.doubleValue();
                                fontLocationRecord.setNumber(tdmcount).setButype(1);
                                result.add(fontLocationRecord);
                            }
                        }
                    }
                }
            }
        }

        jsonObject.put("code", 0);
        jsonObject.put("data", result);
        jsonObject.put("allMoney", allMoney);
        return jsonObject;
    }

    /**
     * 团订更新订单金额
     *
     * @param token        令牌
     * @param orderSn      订单编号
     * @param remark       备注
     * @param shiyang      式样
     * @param modifiedYang 该款打样
     * @param emergency    紧急指数
     * @param orderMoney   订单金额
     * @param brandLabel   品牌标
     */
    @Override
    public int updateTeamOrder(String token, String orderSn, String remark, String shiyang, String
            modifiedYang, String emergency, String orderMoney, String brandLabel) {
        if (!fabricUtil.checkToken(token)) return -1;
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        QueryWrapper<MlccTeamOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccTeamOrderInfo teamOrderInfo = teamOrderMapper.selectOne(wrapper);
        teamOrderInfo.setOrderMoney(orderMoney).setShiyang(shiyang).setModifiedYang(modifiedYang)
                .setEmergency(emergency).setRemark(remark).setStatus(11);

        int updateById = teamOrderMapper.updateById(teamOrderInfo);
        if (updateById > 0) {
            // 1、往订单流水表添加数据（添加之前判断之前是否有数据）必须确保一条订单只有一条流水记录
            QueryWrapper<MlccBusinessWaterInfo> businessWaterInfoQueryWrapper = new QueryWrapper<>();
            businessWaterInfoQueryWrapper.eq("order_sn", teamOrderInfo.getOrderSn());
            List<MlccBusinessWaterInfo> waterList = waterInfoMapper.selectList(businessWaterInfoQueryWrapper);
            if (waterList == null || waterList.size() == 0) {
                MlccBusinessWaterInfo wrater = new MlccBusinessWaterInfo();
                wrater.setOrderId(teamOrderInfo.getId() + "").setType(2).setUserId(userDetail.getId() + "")
                        .setCostMoney(teamOrderInfo.getOrderMoney()).setYewuInstructions("正常订单，前端团订提交订单")
                        .setYewuDeatil("提交订单").setStatus(0).setRemark("团订下单提交订单，草稿订单变为未支付团订订单")
                        .setSysOrgCode(userDetail.getOrgCode())
                        .setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername())
                        .setOrderSn(teamOrderInfo.getOrderSn()).setStoreId(teamOrderInfo.getStoreId()).setId(UUID.randomUUID().toString().substring(0, 15));
                waterInfoMapper.insert(wrater);
            }

            // 2、往订单跟踪表添加一条记录
            MlccTrackingOrder trackingOrder = new MlccTrackingOrder();
            trackingOrder.setId(UUID.randomUUID().toString().substring(0, 15)).setOrderSn(teamOrderInfo.getOrderSn())
                    .setThing("提交订单")
                    .setOrderType(2).setRemark("前端提交了团订订单").setCreateBy(userDetail.getUsername())
                    .setUpdateBy(userDetail.getUsername());
            trackingOrderMapper.insert(trackingOrder);
        }
        return updateById;
    }

    /**
     * 给产品添加附加条件（个订、团订都可以使用）
     *
     * @param productID 产品ID
     * @param type      附加条件的类型：1式样，2改款打样，3紧急指数
     * @param fujiaName 附加条件的名称
     * @param price     附加条件的价格
     */
    @Override
    public int changeProFujia(String productID, Integer type, String fujiaName, Double price) {
        MlccProductInfo productInfo = productInfoMapper.selectById(productID);
        if (productInfo != null) {
            if (type == 1) {
                productInfo.setShiyang(fujiaName).setFujiaPrice(new BigDecimal(price));
            } else if (type == 2) {
                productInfo.setModifiedYang(fujiaName).setFujiaPrice(new BigDecimal(price));
            } else if (type == 3) {
                productInfo.setEmergency(fujiaName).setFujiaPrice(new BigDecimal(price));
            }
        }
        return productInfoMapper.updateById(productInfo);
    }

    /**
     * 修改团订的面料购买米数
     *
     * @param orderSn   订单编号
     * @param orderType 订单类型
     * @param fabricid  面料id
     * @param mishu     购买米数
     */
    @Override
    public int changgefabricMishu(String orderSn, Integer orderType, String fabricid, String mishu) {

        QueryWrapper<MlccOrderFabric> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn).eq("fabric_id", fabricid);
        int count = orderFabricMapper.selectCount(wrapper);
        MlccOrderFabric orderFabric = orderFabricMapper.selectOne(wrapper);
        // 客户信息
        MlccUserInfo userDetail = fabricUtil.getuserByOrder(orderSn, orderType);
        double zhekou = 1;
        MlccFabricInfo fabricInfo = fabricInfoMapper.selectById(fabricid);
        // 重新查询面料的价格(拿到了标准单价)
        fabricInfo = fabricUtil.addPrice(fabricInfo, Double.valueOf(mishu));
        if (fabricInfo.getGroupId() != null) {
            // 获取面料折扣
            zhekou = fabricUtil.userFabricDiscount(userDetail.getId() + "", fabricInfo.getGroupId());
        }
        fabricInfo.setKehuzk(zhekou);

        // 计算折后单价
        BigDecimal zhehouPrice = fabricInfo.getFabricPrice().multiply(new BigDecimal(fabricInfo.getKehuzk())).setScale(2, BigDecimal.ROUND_HALF_UP);
        fabricInfo.setAfterPrice(zhehouPrice.doubleValue());
        // 计算面料的总价
        BigDecimal zongjia = zhehouPrice.multiply(new BigDecimal(Double.valueOf(mishu)).setScale(2, BigDecimal.ROUND_HALF_UP));

        // 如果存在记录 更新购买米数
        if (count > 0) {
            orderFabric.setDiscount(zhekou + "").setMishu(mishu).setPrice(fabricInfo.getFabricPrice())
                    .setAllprice(zongjia).setAllprice(zongjia).setZhehouPrice(zhehouPrice);
            return orderFabricMapper.updateById(orderFabric);
        } else {
            // 插入数据
            MlccOrderFabric insert = new MlccOrderFabric();
            insert.setOrderSn(orderSn).setOrderType(orderType).setMishu(mishu).setFabricId(fabricid)
                    .setPrice(fabricInfo.getFabricPrice()).setAllprice(zongjia)
                    .setDiscount(zhekou + "").setZhehouPrice(zhehouPrice);
            return orderFabricMapper.insert(insert);
        }
    }

    /**
     * 修改团订的面料购买米数 （客供面料专用）
     *
     * @param orderSn   订单编号
     * @param orderType 订单类型
     * @param fabricid  面料id
     * @param mishu     购买米数
     * @param proid     产品id
     * @param remark    备注
     */
    @Override
    public int changgefabricMishuke(String orderSn, Integer orderType, String fabricid, String mishu, String proid, String remark) {

        QueryWrapper<MlccOrderFabric> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn).eq("fabric_id", fabricid).eq("productid", proid);
        int count = orderFabricMapper.selectCount(wrapper);
        MlccOrderFabric orderFabric = orderFabricMapper.selectOne(wrapper);
        // 如果存在记录 更新购买米数
        if (count > 0) {
            orderFabric.setMishu(mishu).setRemark(remark);
            return orderFabricMapper.updateById(orderFabric);
        } else {
            // 插入数据
            MlccOrderFabric insert = new MlccOrderFabric();
            insert.setOrderSn(orderSn).setOrderType(orderType).setMishu(mishu).setFabricId(fabricid)
                    .setProductid(proid).setRemark(remark);
            return orderFabricMapper.insert(insert);
        }
    }

    /**
     * 获取个团定单的收费服务项（里布、低领尼、纽扣）
     *
     * @param orderSn 团订订单编号
     */
    @Override
    public JSONObject shouFeifuwuXiang(String orderSn) {
        JSONObject result = new JSONObject();
        ArrayList<FuwujiaEntity> list = new ArrayList<>();
        BigDecimal allprice = new BigDecimal(0);
        // 1、查询订单下的小产品并且进行分组
        List<MyteamPriceProduct> products = teamOrderAafterTMapper.listpriceProduuct(orderSn);
        if (products != null && products.size() > 0) {
            for (MyteamPriceProduct product : products) {
                // 拿到每一个产品的基本信息
                MlccProductInfo productInfo = productInfoMapper.selectById(product.getId());
                // 非空
                if (productInfo != null) {
                    // 获取品类信息
                    String plid = fabricUtil.getpingleiFromProduct(productInfo);
                    MlccCategoryInfo categoryInfo = categoryInfoMapper.selectById(plid);
                    // 计算里布的价格
                    if (productInfo.getLibuId() != null) {
                        MlccMaterialLibuInfo libuInfo = libuInfoMapper.selectById(productInfo.getLibuId());
                        if (libuInfo != null && libuInfo.getSalesPrice() != null) {
                            if (libuInfo.getSalesPrice().doubleValue() != 0) {
                                FuwujiaEntity entity = new FuwujiaEntity();
                                entity.setPlname(categoryInfo.getCategoryName()).setName(libuInfo.getLibuCode())
                                        .setProductName(productInfo.getProductName()).setNum(product.getNum())
                                        .setType("里布")
                                        .setPrice(libuInfo.getSalesPrice().multiply(new BigDecimal(product.getNum())));
                                allprice = allprice.add(entity.getPrice());
                                list.add(entity);
                            }
                        }
                    }

                    // 计算低领尼的价格
                    if (productInfo.getDilinliId() != null) {
                        MlccDilinniInfo dilinniInfo = dilinniInfoMapper.selectById(productInfo.getDilinliId());
                        if (dilinniInfo != null && dilinniInfo.getSalesPrice() != null) {
                            if (dilinniInfo.getSalesPrice().doubleValue() != 0) {
                                FuwujiaEntity entity = new FuwujiaEntity();
                                entity.setPlname(categoryInfo.getCategoryName()).setName(dilinniInfo.getDilinniNumber())
                                        .setProductName(productInfo.getProductName()).setNum(product.getNum())
                                        .setType("底领呢")
                                        .setPrice(dilinniInfo.getSalesPrice().multiply(new BigDecimal(product.getNum())));
//                            allprice += dilinniInfo.getSalesPrice().doubleValue();
                                allprice = allprice.add(entity.getPrice());
                                list.add(entity);
                            }
                        }
                    }

                    // 计算纽扣的钱
                    if (productInfo.getButtonsIds() != null) {
                        MlccButtonsInfo buttonsInfo = buttonsInfoMapper.selectById(productInfo.getButtonsIds());
                        if (buttonsInfo != null && buttonsInfo.getRetailPrice() != null) {
                            if (buttonsInfo.getRetailPrice().doubleValue() != 0) {
                                FuwujiaEntity entity = new FuwujiaEntity();
                                entity.setPlname(categoryInfo.getCategoryName()).setName(buttonsInfo.getButtonsName())
                                        .setProductName(productInfo.getProductName()).setNum(product.getNum())
                                        .setType("纽扣")
                                        .setPrice(buttonsInfo.getRetailPrice().multiply(new BigDecimal(product.getNum())));
//                            allprice += buttonsInfo.getRetailPrice().doubleValue();
                                allprice = allprice.add(entity.getPrice());
                                list.add(entity);
                            }
                        }
                    }
                }
            }
        }
        result.put("code", 0);
        result.put("data", list);
        result.put("price", allprice.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        return result;
    }

    /**
     * 员工详情
     *
     * @param smallProid 小产品id
     */
    @Override
    public MlccCustomerInfo deppDetail(String smallProid) {
        MlccCustomerProductInfo info = smallProductMapper.selectById(smallProid);
        if (info != null) {
            MlccCustomerInfo customerInfo = customeInfoMapper.selectById(info.getCustomerId());
            return customerInfo;
        }
        return null;
    }

    /**
     * 根据部门id（采购项）导出人员列表excel
     *
     * @param departId 部门id
     */
    @Override
    public List<MlccCustomerInfo> departProExcel(String departId) {
        // 存放结果
        ArrayList<MlccCustomerInfo> result = new ArrayList<>();
        // 查询部门下的所有小产品
        QueryWrapper<MlccCustomerProductInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("depart_id", departId);
        List<MlccCustomerProductInfo> list = smallProductMapper.selectList(wrapper);

        if (list != null && list.size() > 0) {
            for (MlccCustomerProductInfo info : list) {
                // 查询小产品对应的人员信息
                MlccCustomerInfo customerInfo = customeInfoMapper.selectById(info.getCustomerId());

                // 查询小产品量体信息
                List<ProSize> proSizes = teamOrderAafterTMapper.listSize(info.getId());
                if (customerInfo != null) {
                    if (info.getBodysType() != 0) {
                        // 标准尺码名称
                        customerInfo.setBsize(info.getStandardSize());
                    }
                    customerInfo.setSizeList(proSizes);
                    // 查询部门名称
                    MlccCustomerDepart depart = customerDepartMapper.selectById(info.getDepartId());
                    if (depart != null) {
                        customerInfo.setDepartName(depart.getDepartName());
                    }
                    // 查询产品名称
                    MlccProductInfo productInfo = productInfoMapper.selectById(info.getProductId());
                    if (productInfo != null) {
                        customerInfo.setProductName(productInfo.getProductName());
                    }
                    result.add(customerInfo);
                }
            }
        }
//        return result.stream().collect(Collectors.groupingBy(MlccCustomerInfo::getProductName));
        return result;
    }

    /**
     * 根据部门id（采购项）导出人员列表excel
     *
     * @param departId 部门id
     */
    @Override
    public void departProExcel2(String departId, HttpServletResponse response) throws Exception {
        ServletOutputStream out = response.getOutputStream();
        // 存放结果
        ArrayList<MlccCustomerInfo> result = new ArrayList<>();
        // 查询部门下的所有小产品
        QueryWrapper<MlccCustomerProductInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("depart_id", departId);
        List<MlccCustomerProductInfo> list = smallProductMapper.selectList(wrapper);

        if (list != null && list.size() > 0) {
            for (MlccCustomerProductInfo info : list) {
                // 查询小产品对应的人员信息
                MlccCustomerInfo customerInfo = customeInfoMapper.selectById(info.getCustomerId());

                // 查询小产品量体信息
                List<ProSize> proSizes = teamOrderAafterTMapper.listSize(info.getId());
                if (customerInfo != null) {
                    if (info.getBodysType() != 0) {
                        // 标准尺码名称
                        customerInfo.setBsize(info.getStandardSize());
                    }
                    customerInfo.setSizeList(proSizes);
                    // 查询部门名称
                    MlccCustomerDepart depart = customerDepartMapper.selectById(info.getDepartId());
                    if (depart != null) {
                        customerInfo.setDepartName(depart.getDepartName());
                    }
                    // 查询产品名称
                    MlccProductInfo productInfo = productInfoMapper.selectById(info.getProductId());
                    if (productInfo != null) {
                        customerInfo.setProductName(productInfo.getProductName()).setProductid(productInfo.getId());
                    }
                    result.add(customerInfo);
                }
            }
        }
        Map<String, List<MlccCustomerInfo>> sheets = result.stream().collect(Collectors.groupingBy(MlccCustomerInfo::getProductid));


        // key是产品id，value是这个大产品对应的人员列表
        //excel导出的路径和名称
//        OutputStream out = new FileOutputStream("D:\\test.xls");
        try {
            MyExcelUtils eeu = new MyExcelUtils();
            HSSFWorkbook workbook = new HSSFWorkbook();
            // 遍历得到的数据
            int j = 0;
            for (String productid : sheets.keySet()) {
                List<MlccCustomerInfo> customerInfos = sheets.get(productid);
                MlccProductInfo info = productInfoMapper.selectById(productid);
                if (info != null) {
//                    String[] siziids = info.getBodySizeIds().split(",");
                    // 根据产品获取品类id
                    String PLID = fabricUtil.getpingleiFromProduct(info);
                    System.out.println("品类id是多少==============" + PLID);
                    // 根据品类id获取尺寸信息
                    // 存放所有产品所有查询到的尺寸id
                    ArrayList<Integer> bodyresult = new ArrayList<>();
                    QueryWrapper<MlccBodySizeInfo> selectSizeWrapper = new QueryWrapper<>();
                    selectSizeWrapper.eq("category_id", PLID).eq("status", 0);
                    List<MlccBodySizeInfo> bodySizeInfos = bodySizeMapper.selectList(selectSizeWrapper);
                    if (bodySizeInfos != null && bodySizeInfos.size() > 0) {
                        for (MlccBodySizeInfo sizeInfo : bodySizeInfos) {
                            bodyresult.add(sizeInfo.getId());
                        }
                    }
                    // 查询尺寸信息
                    QueryWrapper<MlccBodySizeInfo> wrapper1 = new QueryWrapper<>();
                    wrapper1.in("id", bodyresult);
                    List<MlccBodySizeInfo> sizeInfos = bodySizeMapper.selectList(wrapper1);
                    List<String> baseTitle = MyExcelUtils.baseTitle();
                    // 将尺寸集合中的名称拿出来，作为一个sheet的表头(并不完整，还需要添加人员的信息)
                    List<String> head = sizeInfos.stream().map(MlccBodySizeInfo::getBodySizename).collect(Collectors.toList());
                    baseTitle.addAll(head);
                    // 单个sheet的数据
                    List<List<String>> productdata = new ArrayList<List<String>>();

                    // 遍历单个sheet的每个客户
                    for (MlccCustomerInfo customerInfo : customerInfos) {
                        // 存放行的数据
                        ArrayList<String> rowData = new ArrayList<>();
                        // 设置基本数据
                        rowData.add(customerInfo.getCustomerCode());
                        rowData.add(customerInfo.getCustomerName());
                        rowData.add(customerInfo.getSex() == 1 ? "男" : "女");
                        rowData.add(customerInfo.getDefaultValue1());
                        rowData.add(customerInfo.getDefaultValue2());
                        rowData.add(customerInfo.getDefaultValue3());
                        rowData.add(customerInfo.getDefaultValue4());
                        rowData.add(customerInfo.getDefaultValue5());
                        rowData.add(customerInfo.getDefaultValue6());
                        rowData.add(customerInfo.getDepartName());
                        rowData.add(customerInfo.getProductName());
                        rowData.add(customerInfo.getBsize());
                        // 设置量体数据
                        // 遍历当前客户的尺寸数据
                        for (int k = 0; k < baseTitle.size(); k++) {
                            if (k >= 12 && k < baseTitle.size()) {
                                if (customerInfo != null) {
                                    List<ProSize> sizeList = customerInfo.getSizeList();
                                    for (ProSize proSize : sizeList) {
                                        // 如果标题和尺码的名称一致
                                        if (baseTitle.get(k).equals(proSize.getBodySizename())) {
                                            rowData.add(proSize.getBodysizeValue());
                                        }
                                    }
                                }
                            }
                        }
                        productdata.add(rowData); // 数据就绪完毕
                        // 遍历终止
                    }
                    String[] objects = baseTitle.toArray(new String[baseTitle.size()]);
                    eeu.exportExcel(workbook, j, info.getProductName(), objects, productdata, out);
                    j++;
                }
            }

            //将所有的数据一起写入，然后再关闭输入流。
            workbook.write(out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            out.close();
        }

    }

    /**
     * 团订申请售后，根据员工工号获取名下小产品列表
     *
     * @param code 员工工号
     */
    @Override
    public List<MlccProductInfo> getSmallProductListByEmpCode(String code, String orderSn) {
        // 存放所有的结果
        ArrayList<MlccProductInfo> result = new ArrayList<>();
        // 查询到具体的人员
        QueryWrapper<MlccTeamOrderInfo> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("order_sn", orderSn);
        MlccTeamOrderInfo teamOrderInfo = teamOrderMapper.selectOne(wrapper1);
        QueryWrapper<MlccCustomerInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("customer_code", code).eq("parentId", teamOrderInfo.getCustomerId());
        MlccCustomerInfo customerInfo = customeInfoMapper.selectOne(wrapper);
        if (customerInfo != null) {
            // 根据人员查询名下所有的小产品
            QueryWrapper<MlccCustomerProductInfo> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("customer_id", customerInfo.getId()).eq("team_order_sn", orderSn);
            List<MlccCustomerProductInfo> mlccCustomerProductInfos = smallProductMapper.selectList(wrapper2);
            if (mlccCustomerProductInfos != null && mlccCustomerProductInfos.size() > 0) {
                for (MlccCustomerProductInfo info : mlccCustomerProductInfos) {
                    MlccProductInfo info1 = productInfoMapper.selectById(info.getProductId());
                    if (info1 != null) {
                        // 需要用到小产品编号
                        info1.setSmallCode(info.getCode());
                        result.add(info1);
                    }
                }
            }
        }
        return result;
    }

    /*-------------------------------工具方法-------------------------------------------*/

    /**
     * 团订模板详情
     *
     * @param orderSn 订单编号
     */
    public MlccTeamModuleInfo moduleDetail(String orderSn) {
        QueryWrapper<MlccTeamModuleInfo> wrapper = new QueryWrapper<>();
        List<MlccFabricInfo> infos = new ArrayList<>(); // 存放订单里所有的面料
        List<MlccProductInfo> allPro = new ArrayList<>();// 存放订单下所有产品
        double fabricPriceAll = 0; // 订单下所有面料的价格
        double proPriceAall = 0; // 订单下所有产品的价格（加工费用）
        wrapper.eq("order_sn", orderSn);
        MlccTeamModuleInfo info = teamMudoleMapper.selectOne(wrapper);// 首先拿到了产品
        // 创建一个变量，用来计算订单价格
        double orderMoney = 0;
        if (info != null && info.getCustomerId() != null) {
            /*1、订单里的部门列表*/
            QueryWrapper<MlccCustomerDepart> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("customer_id", info.getCustomerId());
            List<MlccCustomerDepart> departList = customerDepartMapper.selectList(wrapper1);// 这里拿到了所有部门
            if (departList != null && departList.size() > 0) {
                for (MlccCustomerDepart depart : departList) {
                    /*2、接下来查询部门下的所有员工*/
                    QueryWrapper<MlccCustomerInfo> wrapper2 = new QueryWrapper<>();
                    wrapper2.eq("depart_id", depart.getId()).eq("is_company", 0);
                    depart.setCustomerInfoList(customeInfoMapper.selectList(wrapper2));

                    /*新需求，查询部门下的小产品，替代部门下的人员ID*/
                    QueryWrapper<MlccCustomerProductInfo> customerProductInfoQueryWrapper = new QueryWrapper<>();
                    customerProductInfoQueryWrapper.eq("team_order_sn", orderSn).eq("depart_id", depart.getId());
                    List<MlccCustomerProductInfo> mlccCustomerProductInfos = SmallProductMapper.selectList(customerProductInfoQueryWrapper);
                    for (MlccCustomerProductInfo customerProductInfo : mlccCustomerProductInfos) {
                        // 查人员
                        MlccCustomerInfo customerInfo = customeInfoMapper.selectById(customerProductInfo.getCustomerId());
                        // 查产品
                        MlccProductInfo mlccProductInfo = productInfoMapper.selectById(customerProductInfo.getProductId());
                        // 赋值
                        customerProductInfo.setCustomerName(customerInfo.getCustomerName()).setSex(customerInfo.getSex())
                                .setCustomerCode(customerInfo.getCustomerCode()).setProductName(mlccProductInfo.getProductName());

                    }
                    depart.setSmallPro(mlccCustomerProductInfos);

                    /*3、得到部门下产品列表*/
                    QueryWrapper<MlccDepartProduct> wrapper3 = new QueryWrapper<>();
                    wrapper3.eq("customer_depart_id", depart.getId());
                    List<MlccDepartProduct> departProducts = departProductMapper.selectList(wrapper3);// 所有的部门产品关联
                    ArrayList<MlccProductInfo> productInfos = new ArrayList<>(); // 用来存放部门下所有的产品
                    // 查询部门下的所有产品
                    if (departProducts != null && departProducts.size() > 0) {
                        for (MlccDepartProduct departProduct : departProducts) {
                            QueryWrapper<MlccProductInfo> mlccProductInfoQueryWrapper = new QueryWrapper<>();
                            mlccProductInfoQueryWrapper.eq("id", departProduct.getProductId());
                            MlccProductInfo mlccProductInfo = productInfoMapper.selectOne(mlccProductInfoQueryWrapper);
                            if (mlccProductInfo != null) {
                                productInfos.add(mlccProductInfo);
                                allPro.add(mlccProductInfo);
                            }
                        }
                    }
                    if (productInfos != null && productInfos.size() > 0) {
                        /*4、接下来要查询产品里的信息*/
                        for (MlccProductInfo newProductInfo : productInfos) {
                            // 1、查询产品的数量
                            if (newProductInfo.getCategoryIds() != null) {
                                List<String> CategoryIdSet = Arrays.asList(newProductInfo.getCategoryIds().split(","));// 每个产品中的类别ID
                                /*2、品类版型的查询（产品数据中categoryid对应数据的isType为1的数据）*/
                                QueryWrapper<MlccCategoryInfo> wrapper4 = new QueryWrapper<>();
                                wrapper4.in("id", CategoryIdSet).eq("is_type", 1);
                                List<MlccCategoryInfo> plbxs = categoryInfoMapper.selectList(wrapper4);
                                // 给每一个品类查询他的上级名称，就是模块下的小模块表的名称
                                if (plbxs != null && plbxs.size() > 0) {
                                    for (MlccCategoryInfo plbx : plbxs) {
                                        if (plbx != null && plbx.getParentId() != null) {
                                            MlccModuleSmallTemplate smallTemplate = moduleSmallTemplateMapper.selectById(plbx.getParentId());
                                            if (smallTemplate != null && smallTemplate.getParameter() != null) {
                                                plbx.setSmallTemplateName(smallTemplate.getParameter());
                                            }
                                        }
                                    }
                                    newProductInfo.setPlbx(plbxs);
                                }
                            }
                            // 3、从产品数据中查询面料与辅料数据
                            if (newProductInfo.getFabricIds() != null && !"".equals(newProductInfo.getFabricIds())) {
                                HashSet<MlccFabricInfo> fabricInfoSet = new HashSet<>();
                                List<String> fabricids = Arrays.asList(newProductInfo.getFabricIds().split(","));// 面料id/米数这种格式
                                for (String fabricid : fabricids) {
                                    String[] split = fabricid.split("/");
                                    MlccFabricInfo mlccFabricInfos = fabricInfoMapper.selectById(split[0]);
                                    mlccFabricInfos.setMishu(split[1]);
                                    fabricInfoSet.add(mlccFabricInfos);
                                }
                                // 查询面料的价格
                                HashSet<MlccFabricInfo> fabricprice = fabricUtil.addPrice(fabricInfoSet);
                                fabricprice = fabricUtil.addkhzktdModule(orderSn, fabricprice);
                                ArrayList<MlccFabricInfo> arrayList = new ArrayList<>(fabricprice);
                                // 计算面料价格
                                for (MlccFabricInfo fabricInfo : arrayList) {
                                    // 计算折后单价
                                    fabricInfo.setAfterPrice(fabricInfo.getFabricPrice().doubleValue() * fabricInfo.getKehuzk());
                                    // 计算单重面料的总价
                                    fabricInfo.setAllPrice(fabricInfo.getAfterPrice() * Double.valueOf(fabricInfo.getMishu()));
                                    orderMoney += fabricInfo.getAllPrice();
                                    // 向全体面料列表添加面料数据
                                    infos.add(fabricInfo);
                                    fabricPriceAll += fabricInfo.getAllPrice();
                                }
                                newProductInfo.setFabricList(arrayList);
                            }

                            /*下一步。。。*/
                            if (newProductInfo.getCategoryIds() != null) {
                                List<String> CategoryIdSet = Arrays.asList(newProductInfo.getCategoryIds().split(","));// 每个产品中的类别ID
                                // 4、查询款式与工艺（根据categoryid来查询，但是is_type必须为0）
                                QueryWrapper<MlccCategoryInfo> wrapper4 = new QueryWrapper<>();
                                wrapper4.in("id", CategoryIdSet).eq("is_type", 0);
                                List<MlccCategoryInfo> ksgys = categoryInfoMapper.selectList(wrapper4);
                                // 给每一个品类查询他的上级名称，就是模块下的小模块表的名称
                                for (MlccCategoryInfo ksgy : ksgys) {
                                    ksgy.setSmallTemplateName(moduleSmallTemplateMapper.selectById(ksgy.getParentId()).getParameter());
                                }
                                newProductInfo.setKsgy(ksgys);
                            }

                            /*下一步*/
                            // 6、撞色数据
                            if (newProductInfo.getZhuangseIds() != null) {
                                HashSet<String> hzuangseidSet = new HashSet<>();// 遍历获取撞色ID
                                String[] hzuangseidArray = newProductInfo.getZhuangseIds().split(",");
                                for (String zhuangseid : hzuangseidArray) {
                                    hzuangseidSet.add(zhuangseid);
                                }
                                if (hzuangseidSet.size() > 0) {
                                    QueryWrapper<MlccContrastcolorInfo> wrapper5 = new QueryWrapper<>();
                                    wrapper3.in("id", hzuangseidSet);
                                    // 现在拿到了所有的撞色数据，但是还没有具体的颜色
                                    List<MlccContrastcolorInfo> contrastcolorInfos = contrastColorMapper.selectList(wrapper5);
                                    for (MlccContrastcolorInfo everyConColoer : contrastcolorInfos) {
                                        if (everyConColoer.getEmColorId() != null && !"".equals(everyConColoer.getEmColorId())) {
                                            everyConColoer.setColorName(embroColorMapper.selectById(everyConColoer.getEmColorId()).getColorName());
                                        }
                                    }
                                    newProductInfo.setAllConColor(contrastcolorInfos);
                                }
                            }
                            /*下一步*/
                            // 7、获取产品中的尺寸信息(身体数据，注意与体型表区别)
                            if (newProductInfo.getBodySizeIds() != null) {
                                HashSet<MlccProductBodysize> bodySizeSet = new HashSet<>();
                                // 用产品ID可以到达产品尺寸关联表
                                QueryWrapper<MlccProductBodysize> wrapper5 = new QueryWrapper<>();
                                wrapper5.eq("product_id", newProductInfo.getId());
                                List<MlccProductBodysize> productBodysizes = productBodySizeMapper.selectList(wrapper5);
                                for (MlccProductBodysize bodysize : productBodysizes) {
                                    bodySizeSet.add(bodysize);
                                }
                                for (MlccProductBodysize probodysize : bodySizeSet) {
                                    String categoryId = bodySizeMapper.selectById(probodysize.getBodysizeId()).getCategoryId();
                                    probodysize.setTypeName(categoryInfoMapper.selectById(categoryId).getCategoryName());
                                    probodysize.setSizeName(bodySizeMapper.selectById(probodysize.getBodysizeId()).getBodySizename());
                                    probodysize.setUnit(bodySizeMapper.selectById(probodysize.getBodysizeId()).getUnit());
                                }
                                newProductInfo.setProductBodySizeList(bodySizeSet);
                            }

                            /*下一步*/
                            // 8、加工费用（也就是产品费用）
                            if (newProductInfo.getZhehouPrice() != null) {
                                double orderPrice = 0;
                                Double kehuzhekou = fabricUtil.getkhzktdModule(orderSn);// 客户折扣
                                newProductInfo.setKhzk(kehuzhekou);
                                newProductInfo.setAfterzhekouPrice(newProductInfo.getZhehouPrice().doubleValue() * kehuzhekou);
                                newProductInfo.setAllPrice(newProductInfo.getZhehouPrice().doubleValue() * kehuzhekou);
                                orderPrice += newProductInfo.getAllPrice();
                            }

                            /*下一步*/
                            // 9、查询纽扣列表
                            if (newProductInfo.getButtonsIds() != null) {
                                List<String> buttonIDList = Arrays.asList(newProductInfo.getButtonsIds().split(","));
                                QueryWrapper<MlccButtonsInfo> buttonwrapper = new QueryWrapper<>();
                                buttonwrapper.in("id", buttonIDList);
                                newProductInfo.setButtonsInfoList(buttonsInfoMapper.selectList(buttonwrapper));
                            }

                            /*下一步*/
                            // 10、查询体型数据
                            if (newProductInfo.getSizeIds() != null) {
                                List<String> sizeIds = Arrays.asList(newProductInfo.getSizeIds().split(","));
                                QueryWrapper<MlccSizeInfo> sizeInfoQueryWrapper = new QueryWrapper<>();
                                sizeInfoQueryWrapper.in("id", sizeIds);
                                List<MlccSizeInfo> mlccSizeInfoList = sizeInfoMapper.selectList(sizeInfoQueryWrapper);// 这个时候还需要拿到父级的名称
                                for (MlccSizeInfo mlccSizeInfo : mlccSizeInfoList) {
                                    if (mlccSizeInfo != null && !"0".equals(mlccSizeInfo.getParentId())) {
                                        mlccSizeInfo.setSizeName(sizeInfoMapper.selectById(mlccSizeInfo.getParentId()).getSizeName());
                                    }
                                }
                                newProductInfo.setSizeInfoList(mlccSizeInfoList);
                            }
                            /*下一步*/
                            // 11 计算订单金额
                            if (newProductInfo.getZhehouPrice() != null) {
                                Double khzk = fabricUtil.getkhzktdModule(orderSn);
                                // 计算出产品的折后价格
                                double proPrice = newProductInfo.getZhehouPrice().doubleValue() * khzk;
                                orderMoney += proPrice;
                            }
                            proPriceAall += newProductInfo.getAfterzhekouPrice();
                        }
                    }
                    depart.setProductInfos(productInfos);
                }
            }

            info.setDeparts(departList);// 部门里以经查到了下面的员工和产品信息
        }
        info.setAllFabric(infos).setFabricPriceAll(fabricPriceAll).setAllPro(allPro).setProPriceAall(proPriceAall);
        return info;
    }

    /**
     * 向订单事件表添加记录
     *
     * @param orderType 默认0，面料订单，1个订订单，2团订订单，3成衣订单
     * @param type      默认0日常处理，1紧急事件
     * @param eventName 事件名称
     * @param what      事件类型，1支付，2售后
     * @param afterid   售后订单id
     * @param afterCode 售后订单编号
     */
    public void inserEvent(Integer orderType, Integer type, String eventName, Integer what, String afterid, String afterCode) {
        MlccEventRecrodInfo info = new MlccEventRecrodInfo();
        info.setEventName(eventName).setType(type).setOrderType(orderType);
        if (what == 2) {
            // 售后加数据
            info.setAfterorderId(afterid).setAfterorderCode(afterCode);
        }
        eventRecrodInfoMapper.insert(info);
    }

    /**
     * 判断这个小产品是否正处于售后状态中
     *
     * @param code 小产品编号
     */
    boolean smallProisFan(String code) {
        QueryWrapper<MlccCustomerProductInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("code", code);
        MlccCustomerProductInfo one = smallProductMapper.selectOne(wrapper);
        if (one != null) {
            QueryWrapper<MlccAfterSalesinfo> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("order_sn", one.getTeamOrderSn()).eq("status", 0);
            List<MlccAfterSalesinfo> list = afterSalesinfoMapper.selectList(wrapper1);
            if (list != null && list.size() > 0) {
                for (MlccAfterSalesinfo salesinfo : list) {
                    if (salesinfo.getAfterstatus() != 3 && salesinfo.getAfterstatus() != 1) {
                        // 刚刚提交订单的情况，看看未处理的售后订单里面是否有这个小产品
                        if (salesinfo.getAfterstatus() == 0) {
                            // 此时找到了这个订单下的未完成售后顶动感
                            // 判断这个售后订单下的小产品是否包含传进来的小产品
                            List<MyAfterProduct> smallPro2 = mapper.getAfterSmallPro2(salesinfo.getAfterCode());
                            if (smallPro2 != null && smallPro2.size() > 0) {
                                for (MyAfterProduct product : smallPro2) {
                                    if (product.getCode().equals(code)) {
                                        return true;
                                    }
                                }
                            }
                            // 说明后端已经操作了这个售后订单，再去售后小产品查是否有这个产品
                            QueryWrapper<MlccTrackafterorderPerson> wrapper2 = new QueryWrapper<>();
                            wrapper2.eq("after_sn", salesinfo.getAfterCode()).eq("small_product_id", one.getId());
                            int count = trackafterorderPersonMapper.selectCount(wrapper2);
                            if (count > 0) {
                                return true;
                            }
                        } else {
                            // 说明后端已经操作了这个售后订单，再去售后小产品查是否有这个产品
                            QueryWrapper<MlccTrackafterorderPerson> wrapper2 = new QueryWrapper<>();
                            wrapper2.eq("after_sn", salesinfo.getAfterCode()).eq("small_product_id", one.getId());
                            int count = trackafterorderPersonMapper.selectCount(wrapper2);
                            if (count > 0) {
                                return true;
                            }
                        }
                    }
                }
            }
        }
        return false;
    }
}
